Sort Transformed Array - Problem

Given a sorted integer array nums and three integers a, b and c, apply a quadratic function of the form f(x) = ax² + bx + c to each element nums[i] in the array, and return the array in a sorted order.

The quadratic function transforms each element, and the resulting values need to be sorted before returning.

Note: The input array is already sorted, but after applying the quadratic transformation, the order may change depending on the coefficients.

Input & Output

Example 1 — Upward Parabola
$ Input: nums = [-4,-2,2,4], a = 1, b = 3, c = 5
Output: [3,9,15,33]
💡 Note: f(x) = x² + 3x + 5. f(-4) = 16-12+5 = 9, f(-2) = 4-6+5 = 3, f(2) = 4+6+5 = 15, f(4) = 16+12+5 = 33. Sorted: [3,9,15,33]
Example 2 — Downward Parabola
$ Input: nums = [-2,-1,0,1,2], a = -1, b = 2, c = 1
Output: [-7,-2,1,1,2]
💡 Note: f(x) = -x² + 2x + 1. f(-2) = -4-4+1 = -7, f(-1) = -1-2+1 = -2, f(0) = 1, f(1) = -1+2+1 = 2, f(2) = -4+4+1 = 1. Sorted: [-7,-2,1,1,2]
Example 3 — Linear Case
$ Input: nums = [1,2,3], a = 0, b = 2, c = 1
Output: [3,5,7]
💡 Note: f(x) = 2x + 1 (linear). f(1) = 3, f(2) = 5, f(3) = 7. Already sorted since input is sorted and coefficient is positive.

Constraints

  • 1 ≤ nums.length ≤ 200
  • -100 ≤ nums[i] ≤ 100
  • -104 ≤ a, b, c ≤ 104
  • nums is sorted in non-decreasing order

Visualization

Tap to expand
Sort Transformed Array f(x) = ax² + bx + c INPUT Sorted Array nums[] -4 -2 2 4 Quadratic Parameters a = 1 b = 3 c = 5 Parabola (a > 0: opens up) vertex (min) f(-4)=9, f(-2)=3, f(2)=15, f(4)=33 ALGORITHM STEPS 1 Two Pointers Setup left=0, right=n-1 2 Check a's Sign a>0: fill from end (large first) 3 Compare Endpoints Compare f(left) vs f(right) 4 Place & Move Pointer Move left++ or right-- -4 -2 2 4 L R Time: O(n) | Space: O(n) Single pass with two pointers FINAL RESULT Transformation Process f(-4) = 1(16) + 3(-4) + 5 = 9 f(-2) = 1(4) + 3(-2) + 5 = 3 f(2) = 1(4) + 3(2) + 5 = 15 f(4) = 1(16) + 3(4) + 5 = 33 Two-Pointer Sorting Unsorted: [9, 3, 15, 33] Compare ends, place larger: 33 > 9 --> place 33 at end 15 > 9 --> place 15 9 > 3 --> place 9 place 3 Sorted Output 3 9 15 33 OK - Sorted in O(n)! Key Insight: For a quadratic with a > 0, the parabola opens upward, so extreme values (min at edges) are at the endpoints. We use two pointers to compare f(left) and f(right), placing the larger value at the end of result array and moving the corresponding pointer inward. This achieves O(n) time. TutorialsPoint - Sort Transformed Array | Optimal Two-Pointer Approach
Asked in
Google 25 Facebook 18 Microsoft 12
28.0K Views
Medium Frequency
~18 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen