Merge Sorted Quadratic Outputs in Linear Time
Arrays & HashingAuto-graded · 24 test casesLast updated
Evaluate a quadratic polynomial on a sorted array and return sorted results without using O(n log n) sorting
You are given an integer array nums sorted in non-decreasing order and three integer coefficients a, b, and c representing the polynomial p(x) = a*x² + b*x + c.
Compute p(x) for every element x in nums and return all results in non-decreasing sorted order.
Note that a can be positive, negative, or zero, which affects the shape of the polynomial curve.
Parameters
nums: A sorted array of integers (non-decreasing order, may contain duplicates)a,b,c: Integer coefficients of the polynomial
Return Value
A list containing p(nums[i]) for each index i, sorted in non-decreasing order. The output has the same length as the input.
Constraints
1 <= len(nums) <= 10^5-10^4 <= nums[i] <= 10^4numsis sorted in non-decreasing order-10^4 <= a, b, c <= 10^4- All output values fit within 64-bit signed integers
Examples
Example 1
Input: sorted_polynomial_values([-3, -1, 0, 2, 5], -1, 2, 1)
Output: [-14, -14, -2, 1, 1]
Example 2
Input: sorted_polynomial_values([-2, 1, 3, 3], 0, -3, 4)
Output: [-5, -5, 1, 10]
Example 3
Input: sorted_polynomial_values([-5, -2, 0, 1, 4], 2, 0, -3)
Output: [-3, -1, 5, 29, 47]
Hints
Hint 1
Think about what happens to the polynomial values as you move through the sorted input. When a > 0, the parabola opens upward; when a < 0, it opens downward; when a = 0, it's just a line.
Hint 2
For a parabola opening upward (a > 0), the transformed values decrease then increase. Where are the extreme values? Can you fill the result array from one end using two pointers?
Hint 3
Handle the linear case (a = 0) separately. If the slope b is non-negative, the values stay sorted. If b is negative, what simple operation gives you sorted output?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The naive approach is to compute all polynomial values and sort them, which takes O(n log n) time. We can do better by exploiting the fact that the input is already sorted and understanding the behavior of quadratic functions.
A quadratic function has three cases based on the leading coefficient a:
-
Upward parabola (a > 0): The function decreases until reaching a minimum at the vertex, then increases. When we evaluate it on a sorted input, we get values that decrease then increase (a valley shape). The largest remaining value in any subrange must be at one of the endpoints.
-
Downward parabola (a < 0): The function increases to a maximum at the vertex, then decreases. Evaluated on sorted input, we get values that increase then decrease (a hill shape). The smallest remaining value in any subrange must be at one of the endpoints.
-
Linear function (a = 0): The polynomial becomes
bx + c. Ifb >= 0, the output stays sorted. Ifb < 0, the output is reverse-sorted.
For the quadratic cases, we use a two-pointer merge strategy similar to merging two sorted lists:
- Upward parabola: Use two pointers at both ends. Fill the result array from the back by repeatedly choosing the larger of the two endpoint values.
- Downward parabola: Use two pointers at both ends. Fill the result array from the front by repeatedly choosing the smaller of the two endpoint values.
This works because in any remaining window, the extreme value (max for upward, min for downward) is guaranteed to be at one of the boundaries.
Correctness
For an upward parabola, the transformed values form a valley: they're non-increasing up to some point, then non-decreasing. Any contiguous subsequence of such a valley maintains this property, so its maximum is at one of its endpoints. By repeatedly taking the maximum and shrinking the window, we place values in descending order, which when filled from the back produces ascending sorted output.
For a downward parabola, the transformed values form a hill: non-decreasing then non-increasing. The minimum of any subrange is at an endpoint. Taking minimums from the front builds the sorted result directly.
Complexity
- Time: O(n) — we evaluate the polynomial n times and perform a single pass with two pointers
- Space: O(n) — for storing the computed values and result array
Solution
from typing import List
def sorted_polynomial_values(nums: List[int], a: int, b: int, c: int) -> List[int]:
n = len(nums)
values = [a * x * x + b * x + c for x in nums]
result = [0] * n
left, right = 0, n - 1
if a > 0 or (a == 0 and b >= 0):
if a == 0:
return values
index = n - 1
while left <= right:
if values[left] >= values[right]:
result[index] = values[left]
left += 1
else:
result[index] = values[right]
right -= 1
index -= 1
else:
if a == 0:
return values[::-1]
index = 0
while left <= right:
if values[left] <= values[right]:
result[index] = values[left]
left += 1
else:
result[index] = values[right]
right -= 1
index += 1
return result