Sort Transformed Array Problem
Description
LeetCode Problem 360.
Given a sorted integer array nums and three integers a, b and c, apply a quadratic function of the form f(x) = ax^2 + bx + c to each element nums[i] in the array, and return the array in a sorted order.
Example 1:
Input: nums = [-4,-2,2,4], a = 1, b = 3, c = 5
Output: [3,9,15,33]
Example 2:
Input: nums = [-4,-2,2,4], a = -1, b = 3, c = 5
Output: [-23,-5,1,7]
Constraints:
1 <= nums.length <= 200-100 <= nums[i], a, b, c <= 100numsis sorted in ascending order.
Follow up: Could you solve it in O(n) time?
Solution
Approach: Two Pointers from Both Ends
Applying f and sorting the results takes O(n log n). We can do it in O(n) by using the shape of a parabola.
For a > 0 the parabola opens upward. As x moves away from the vertex in either direction, f(x) grows. Because nums is sorted, the values farthest from the vertex are at the two ends of the array. So the largest remaining value is always f(nums[i]) or f(nums[j]), where i and j are the two ends of the part not yet placed. Compare the two, write the larger one into the answer from the back, and move that pointer inward.
For a < 0 the parabola opens downward, and the same reasoning gives the smallest remaining value at one of the two ends. Write the smaller one into the answer from the front.
When a = 0, f is a straight line, so it is monotonic, and either rule works. The code uses the "largest at an end" rule for a >= 0. Equal values at both ends are fine: take either one.
Complexity: O(n) time, one step per element. O(1) extra space besides the answer.
class Solution:
def sortTransformedArray(self, nums: List[int], a: int, b: int, c: int) -> List[int]:
def f(x: int) -> int:
return a * x * x + b * x + c
n = len(nums)
ans = [0] * n
i, j = 0, n - 1
# a >= 0: the largest value is at one of the two ends, so fill the answer from the back;
# a < 0: the smallest value is at one of the ends, so fill it from the front
for k in range(n):
fi, fj = f(nums[i]), f(nums[j])
if a >= 0:
if fi > fj:
ans[n - 1 - k] = fi
i += 1
else:
ans[n - 1 - k] = fj
j -= 1
else:
if fi < fj:
ans[k] = fi
i += 1
else:
ans[k] = fj
j -= 1
return ans