Sort Transformed Array — LeetCode 360 Python Solution
MediumLeetCode PremiumArrayMathTwo PointersSorting
- Problem
- #360
- Pattern
- Two Pointers
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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
- Input
- nums = [-4,-2,2,4], a = 1, b = 3, c = 5
- Output
- [3,9,15,33]
Python solution
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the array \textit{nums} auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 360. Sort Transformed Array is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 360. Sort Transformed Array?
- LeetCode 360. Sort Transformed Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 360. Sort Transformed Array?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 360. Sort Transformed Array?
- The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
- What topics does LeetCode 360. Sort Transformed Array cover?
- LeetCode 360. Sort Transformed Array is tagged Array, Math, Two Pointers and Sorting on LeetCode.
- Is LeetCode 360. Sort Transformed Array a premium problem?
- Yes. LeetCode 360. Sort Transformed Array is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.