Produce the Sorted List of Squared Values
Solve this Problemnums sorted in non-decreasing order (it may contain negative values), return a new array holding the square of every element, with the result itself sorted in non-decreasing order.
Squaring can scramble the order — a large negative number produces a large positive square. Since the input is already sorted, you can rebuild the sorted result in a single O(n) pass with two pointers instead of squaring and re-sorting from scratch.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ nums.length ≤ 10⁴ - ◆
-10⁴ ≤ nums[i] ≤ 10⁴ - ◆
nums is sorted in non-decreasing order
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public int[] sortedSquaredValues(int[] nums) { |
| 3 | int n = nums.length; |
| 4 | int[] result = new int[n]; |
| 5 | int left = 0, right = n - 1; |
| 6 | int pos = n - 1; |
| 7 | while (left <= right) { |
| 8 | int leftSq = nums[left] * nums[left]; |
| 9 | int rightSq = nums[right] * nums[right]; |
| 10 | if (leftSq > rightSq) { |
| 11 | result[pos--] = leftSq; |
| 12 | left++; |
| 13 | } else { |
| 14 | result[pos--] = rightSq; |
| 15 | right--; |
| 16 | } |
| 17 | } |
| 18 | return result; |
| 19 | } |
| 20 | } |
| 21 |
044Set left and right at the two ends, and pos at the last slot of the result array — we'll fill result from the back with the larger square each round.
Approach & Solutions
Brute Force
BruteSquare every element in a single pass, then sort the resulting array. Simple and correct, but it throws away the fact that the input was already sorted, paying for a full sort we don't strictly need.
O(n log n)O(n)1class Solution {
2 public int[] sortedSquaredValues(int[] nums) {
3 int[] result = new int[nums.length];
4 for (int i = 0; i < nums.length; i++) {
5 result[i] = nums[i] * nums[i];
6 }
7 Arrays.sort(result);
8 return result;
9 }
10}Optimal — Two Pointers
OptimalBecause nums is sorted, the largest square always sits at one of the two ends — either the most negative value or the most positive one. Walk left and right inward, comparing the two candidate squares, and drop the bigger one into the back of a result array. This fills the output from largest to smallest in a single pass, with no sorting needed.
O(n)O(n)1class Solution {
2 public int[] sortedSquaredValues(int[] nums) {
3 int n = nums.length;
4 int[] result = new int[n];
5 int left = 0, right = n - 1;
6 int pos = n - 1;
7 while (left <= right) {
8 int leftSq = nums[left] * nums[left];
9 int rightSq = nums[right] * nums[right];
10 if (leftSq > rightSq) {
11 result[pos--] = leftSq;
12 left++;
13 } else {
14 result[pos--] = rightSq;
15 right--;
16 }
17 }
18 return result;
19 }
20}