Sort the Results of Applying a Quadratic Function to a Sorted Array
WaymoSoftware Engineer · OnsiteLast updated
Apply the quadratic function a*x*x + b*x + c to every element of a sorted integer array and return the results in sorted order, where a may be negative or zero. Tests reasoning about the parabola's shape and merging values from both ends in linear time.
You are given the three integer coefficients a, b and c of the quadratic function f(x) = a*x*x + b*x + c, and an integer array nums sorted in non-decreasing order. Apply f to every element and return the results sorted in non-decreasing order.
Pay attention to the sign of a: it may be negative, and it may also be zero.
Function Signature
def transform_and_sort(nums: list[int], a: int, b: int, c: int) -> list[int]:
Rules
- The output has the same length as
numsand containsf(nums[i])for every indexi, including repeated values. - The output is sorted in non-decreasing order.
Constraints
1 <= len(nums) <= 10^5-10^4 <= nums[i] <= 10^4, andnumsis sorted in non-decreasing order (duplicates allowed).-10^4 <= a, b, c <= 10^4- Every value of
f(nums[i])has absolute value at most about1.0001 * 10^12, which is within2^53.
Examples
Example 1
- Input:
nums = [-3, -1, 0, 2, 5],a = -1,b = 2,c = 1 - Output:
[-14, -14, -2, 1, 1] - Explanation:
f(-3) = -14,f(-1) = -2,f(0) = 1,f(2) = 1,f(5) = -14. With a negativea, the largest values come from the middle of the array.
Example 2
- Input:
nums = [-2, 1, 3, 3],a = 0,b = -3,c = 4 - Output:
[-5, -5, 1, 10] - Explanation: With
a = 0the function is linear and decreasing, so the order of the inputs is reversed.
Example 3
- Input:
nums = [-5, -2, 0, 1, 4],a = 2,b = 0,c = -3 - Output:
[-3, -1, 5, 29, 47]
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.