easyArraysPattern: Two Pointers
Sorted Squares Solution
Problem Statement
You are given a sorted array of integers `numbers`. Compute the square of each element and return the resulting array in sorted order.
Examples
Example 1:
Input:{"numbers":[-3,-1012]}
Output:["01149"]
Explanation: Squares of the input numbers in sorted order: 0^2 = 0, (-1)^2 = 1, 1^2 = 1, 2^2 = 4, (-3)^2 = 9, sorted as [0, 1, 1, 4, 9]
Example 2:
Input:{"numbers":[-5,-2025]}
Output:["0442525"]
Explanation: Squares of the input numbers in sorted order: 0^2 = 0, (-2)^2 = 4, 2^2 = 4, (-5)^2 = 25, 5^2 = 25, sorted as [0, 4, 4, 25, 25]
Constraints
- 1 <= n <= 10^4
- -10^4 <= arr[i] <= 10^4
Time: O(N) Space: O(N)
Two pointers at start and end. Compare absolute values, square the larger one, and place it at the end of a new result array. Move pointer inwards. Time O(N), Space O(N).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
