Transform a Sorted Array with a Quadratic
Arrays & HashingAuto-graded · 20 test casesLast updated
Evaluate a quadratic expression at every element of a sorted array and emit the results in ascending order in linear time.
Problem Statement
You are given nums, a list of integers arranged in non-decreasing order, together with three integer coefficients a, b, and c. Together they specify the expression
f(x) = a·x² + b·x + c
Evaluate f at every element of nums, collect the n resulting integers (where n = len(nums)), and hand them back sorted in non-decreasing order.
The output is a plain list of integers, not a set and not a pair of groups. Positions in nums carry no meaning in the answer — only the multiset of computed values matters. Consequently, when several computed values are equal, they all remain in the output (nothing is deduplicated), and the answer does not depend on which equal value you place first. Two calls with the same inputs must return lists that are identical element by element, so in the presence of ties produce values in non-decreasing order; equal values may appear in any arrangement among themselves.
A few concrete rules to pin down the behavior:
numsmay contain negative numbers, zero, and repeated values.a,b,cmay each be negative, zero, or positive, includinga == 0(a linear or constant expression).- The turning point
x = -b / (2a)(defined only whena != 0) may lie inside, on the boundary of, or entirely outside the range of values covered bynums. Nothing special happens in any of those situations; the same rules apply. - The returned list always has exactly
nentries. - Do not modify
nums.
Reasoning that is acceptable but not required: because nums is sorted, the transformed sequence has at most two monotone runs, so a linear pass is possible. Sorting the computed values directly is O(n log n) and is a valid but slower route.
Constraints
1 <= len(nums) <= 10^5-10^4 <= nums[i] <= 10^4-100 <= a, b, c <= 100numsis sorted in non-decreasing order.- A linear-time solution is expected.
Examples
Example 1
Input: apply_quadratic_sorted([-3, -1, 2, 4], 1, 0, 0)
Output: [1, 4, 9, 16]
Example 2
Input: apply_quadratic_sorted([-3, -2, 1, 4], -1, 2, 1)
Output: [-14, -7, -7, 2]
Hints
Hint 1
A quadratic rises on one side of its turning point and falls on the other, so the transformed values form at most two monotone stretches.
Hint 2
Because `nums` is sorted, the extreme value among the elements not yet emitted always sits at the left or the right edge of the remaining window.
Hint 3
Pick the fill direction from the sign of `a`: with `a > 0` the largest remaining value is at an end (fill the output from the back), otherwise the smallest is at an end (fill it from the front).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because nums is sorted, the sequence of evaluated values f(nums[0]), f(nums[1]), … traces the shape of the parabola:
- When
a > 0the parabola opens upward, so the values dip to a minimum and then climb. The largest value of whatever remains therefore always sits at one of the two ends of the window still to be processed. - When
a <= 0the parabola opens downward (or degenerates into a line or constant), so the values climb and then fall. Now the smallest remaining value always sits at one of the two ends.
That suggests two pointers, lo and hi, delimiting the not-yet-consumed part of nums. Each step evaluates f at both ends and writes exactly one number into the output:
- If
a > 0, write from the back of the output, taking the larger endpoint value and pulling that pointer inward. - If
a <= 0, write from the front of the output, taking the smaller endpoint value and pulling that pointer inward.
Why it is correct
Invariant: at the start of every iteration the unconsumed elements form one contiguous window nums[lo..hi].
For a convex function (a > 0), the maximum over any interval is attained at an endpoint, and the sortedness of nums means those endpoints are exactly nums[lo] and nums[hi]. Comparing f at the two ends therefore identifies the true maximum of everything left, which belongs in the highest still-empty slot. Removing that endpoint leaves a contiguous window, so the argument repeats.
For a <= 0 the symmetric statement holds: the minimum over the window is at an endpoint, so the smaller of the two evaluations is the next value in ascending order and belongs in the lowest still-empty slot.
Equal values are interchangeable, so a tie (lv == rv) can be resolved either way; the code takes the left one. The reasoning never uses the position of the turning point, which is why it works just as well when that point lies outside the range of nums (the sequence is then simply monotone) or on its boundary.
Complexity
- Time:
O(n)— one constant-work iteration per output element. - Space:
O(n)for the result plusO(1)auxiliary space.
Edge cases
n == 1: one evaluation is written and returned.- All-negative or all-positive
nums: the values are monotone; the endpoint comparison still picks the right one. a == 0: the expression is linear and theelsebranch covers it; if additionallyb == 0, every output entry equalsc.- Repeated values in
numscreate ties, handled as above; nothing is deduplicated and the output length staysn. - Magnitudes reach roughly
10^10, fine for Python but beyond 32-bit integers.
from typing import List
def apply_quadratic_sorted(nums: List[int], a: int, b: int, c: int) -> List[int]:
n = len(nums)
out = [0] * n
lo, hi = 0, n - 1
def f(x: int) -> int:
return a * x * x + b * x + c
if a > 0:
# Convex: the largest value still unplaced sits at one of the two ends.
for pos in range(n - 1, -1, -1):
lv, rv = f(nums[lo]), f(nums[hi])
if lv >= rv:
out[pos] = lv
lo += 1
else:
out[pos] = rv
hi -= 1
else:
# Concave or linear: the smallest value still unplaced sits at one of the ends.
for pos in range(n):
lv, rv = f(nums[lo]), f(nums[hi])
if lv <= rv:
out[pos] = lv
lo += 1
else:
out[pos] = rv
hi -= 1
return out