KatInterview

Merge Sorted Quadratic Outputs in Linear Time

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

Last updated

Evaluate a quadratic polynomial on a sorted array and return sorted results without using O(n log n) sorting

You are given an integer array nums sorted in non-decreasing order and three integer coefficients a, b, and c representing the polynomial p(x) = a*x² + b*x + c.

Compute p(x) for every element x in nums and return all results in non-decreasing sorted order.

Note that a can be positive, negative, or zero, which affects the shape of the polynomial curve.

Parameters

  • nums: A sorted array of integers (non-decreasing order, may contain duplicates)
  • a, b, c: Integer coefficients of the polynomial

Return Value

A list containing p(nums[i]) for each index i, sorted in non-decreasing order. The output has the same length as the input.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order
  • -10^4 <= a, b, c <= 10^4
  • All output values fit within 64-bit signed integers

Examples

Example 1

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

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

Example 2

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

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

Example 3

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

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

Hints

Hint 1

Think about what happens to the polynomial values as you move through the sorted input. When a > 0, the parabola opens upward; when a < 0, it opens downward; when a = 0, it's just a line.

Hint 2

For a parabola opening upward (a > 0), the transformed values decrease then increase. Where are the extreme values? Can you fill the result array from one end using two pointers?

Hint 3

Handle the linear case (a = 0) separately. If the slope b is non-negative, the values stay sorted. If b is negative, what simple operation gives you sorted output?