Leetcode #360: Sort Transformed Array
In this guide, we solve Leetcode #360 Sort Transformed Array in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a sorted integer array nums and three integers a, b and c, apply a quadratic function of the form f(x) = ax2 + 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 <= 100 nums is sorted in ascending order.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Math, Two Pointers, Sorting
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: nums = [-4,-2,2,4], a = 1, b = 3, c = 5
Output: [3,9,15,33]
Python Solution
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)
i, j = 0, n - 1
ans = [0] * n
for k in range(n):
y1, y2 = f(nums[i]), f(nums[j])
if a > 0:
if y1 > y2:
ans[n - k - 1] = y1
i += 1
else:
ans[n - k - 1] = y2
j -= 1
else:
if y1 > y2:
ans[k] = y2
j -= 1
else:
ans[k] = y1
i += 1
return ans
Complexity
The time complexity is , and the space complexity is , where is the length of the array . The space complexity is , where is the length of the array .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.