KatInterview

Order Transformed Values of a Sorted Array

Heaps, Sorting & SearchAuto-graded · 23 test cases
MediumAuto-gradedHeaps, Sorting & Searchtwo-pointersarraysmath

Last updated

Apply a quadratic mapping to a sorted list of numbers and return the sorted results in O(n) time.

You are given a list of integers nums arranged in non-decreasing order, alongside three integer coefficients a, b, and c defining the polynomial evaluation function $f(x) = a x^2 + b x + c$.

Compute the value of $f(x)$ for every entry in nums and return a new array containing these transformed values sorted in non-decreasing order.

Your solution must run in $\mathcal{O}(n)$ time, where $n$ is the length of nums.

Constraints

  • $1 \le \text{len}(nums) \le 10^5$
  • $-1000 \le nums[i] \le 1000$
  • nums is sorted in non-decreasing order and may contain duplicate values.
  • $-100 \le a, b, c \le 100$
  • Every intermediate and final calculated value $f(nums[i])$ fits comfortably within standard signed integer limits.

Examples

Example 1

Input: sort_transformed([-4, -2, 2, 4], 1, 3, 5)

Output: [3, 9, 15, 33]

Example 2

Input: sort_transformed([-4, -2, 2, 4], -1, 3, 5)

Output: [-23, -5, 1, 7]

Example 3

Input: sort_transformed([-1, 0, 0, 3], 0, -2, 1)

Output: [-5, 1, 1, 3]

Hints

Hint 1

A quadratic function $f(x) = ax^2 + bx + c$ represents a parabola. Consider how the function values behave at the extremes of an interval depending on the sign of $a$.

Hint 2

When $a > 0$, the parabola opens upwards, meaning the largest values occur at the boundaries (outermost unvisited elements). When $a < 0$, it opens downwards, so the smallest values occur at the boundaries.

Hint 3

Use two pointers starting at both ends of `nums`. Compare their evaluated outputs to populate the result array either from right-to-left (for $a > 0$) or left-to-right (for $a < 0$). Handle $a = 0$ as a special linear case.