KatInterview

Transform a Sorted Array with a Quadratic

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingtwo-pointerssortingmath

Last updated

Evaluate a quadratic expression at every element of a sorted array and emit the results in ascending order in linear time.

Problem Statement

You are given nums, a list of integers arranged in non-decreasing order, together with three integer coefficients a, b, and c. Together they specify the expression

f(x) = a·x² + b·x + c

Evaluate f at every element of nums, collect the n resulting integers (where n = len(nums)), and hand them back sorted in non-decreasing order.

The output is a plain list of integers, not a set and not a pair of groups. Positions in nums carry no meaning in the answer — only the multiset of computed values matters. Consequently, when several computed values are equal, they all remain in the output (nothing is deduplicated), and the answer does not depend on which equal value you place first. Two calls with the same inputs must return lists that are identical element by element, so in the presence of ties produce values in non-decreasing order; equal values may appear in any arrangement among themselves.

A few concrete rules to pin down the behavior:

  • nums may contain negative numbers, zero, and repeated values.
  • a, b, c may each be negative, zero, or positive, including a == 0 (a linear or constant expression).
  • The turning point x = -b / (2a) (defined only when a != 0) may lie inside, on the boundary of, or entirely outside the range of values covered by nums. Nothing special happens in any of those situations; the same rules apply.
  • The returned list always has exactly n entries.
  • Do not modify nums.

Reasoning that is acceptable but not required: because nums is sorted, the transformed sequence has at most two monotone runs, so a linear pass is possible. Sorting the computed values directly is O(n log n) and is a valid but slower route.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • -100 <= a, b, c <= 100
  • nums is sorted in non-decreasing order.
  • A linear-time solution is expected.

Examples

Example 1

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

Output: [1, 4, 9, 16]

Example 2

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

Output: [-14, -7, -7, 2]

Hints

Hint 1

A quadratic rises on one side of its turning point and falls on the other, so the transformed values form at most two monotone stretches.

Hint 2

Because `nums` is sorted, the extreme value among the elements not yet emitted always sits at the left or the right edge of the remaining window.

Hint 3

Pick the fill direction from the sign of `a`: with `a > 0` the largest remaining value is at an end (fill the output from the back), otherwise the smallest is at an end (fill it from the front).