Sort the values of a quadratic function applied to a sorted array in linear time
LinkedInMachine Learning Engineer · Technical ScreenLast updated
Given an integer array sorted in ascending order and the coefficients of a quadratic function, apply the function to every element and return the results in sorted order in linear time. Tests reasoning about the shape of a parabola, handling of positive, negative and zero leading coefficients, and duplicate values.
You are given an integer array nums sorted in non-decreasing order and three integers a, b and c that define the function f(x) = a * x^2 + b * x + c. Apply f to every element of nums and return the resulting values sorted in non-decreasing order. The interviewer asked for a solution that runs in time linear in the length of nums.
Function Signature
def sort_transformed(nums: list[int], a: int, b: int, c: int) -> list[int]:
Rules
- The output contains exactly one value for each element of
nums. Repeated values are kept: equal inputs, or different inputs that map to the same value, each contribute their own copy. - Return the values in non-decreasing order.
amay be positive, negative or zero. Whena = 0the function is linear, and whena = 0andb = 0it is constant.
Constraints
1 <= len(nums) <= 10^5-1000 <= nums[i] <= 1000, andnumsis sorted in non-decreasing order; it may contain duplicates-100 <= a, b, c <= 100- every value
f(nums[i])lies between-100100100and100100100, so all values fit in a 32-bit signed integer
Examples
Example 1
Input: nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5
Output: [3, 9, 15, 33]
f(-4) = 9, f(-2) = 3, f(2) = 15 and f(4) = 33, which in sorted order are [3, 9, 15, 33].
Example 2
Input: nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5
Output: [-23, -5, 1, 7]
f(-4) = -23, f(-2) = -5, f(2) = 7 and f(4) = 1.
Example 3
Input: nums = [-1, 0, 0, 3], a = 0, b = -2, c = 1
Output: [-5, 1, 1, 3]
f(-1) = 3, f(0) = 1 for each of the two zeros, and f(3) = -5.
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.