Squares of a Sorted Array Visualizer & Step-by-Step Algorithm Solution

Square numbers and sort in O(n) time using opposing two pointers.

Category: arrays | Difficulty: Easy

Tags: Two Pointers, Sorted Array

Squares of a Sorted Array

Input Array (nums)
left
-4
0
-1
1
0
2
3
3
right
10
4
Result Squared Array (result)
0
1
2
3
pos
4
100%
state
leftN/A
rightN/A
posN/A
Initialization
1/34
Explanation

Initializing sortedSquares function.

Source Code
1function sortedSquares(nums) {
2 const n = nums.length;
3 const result = new Array(n);
4 let left = 0, right = n - 1, pos = n - 1;
5 while (left <= right) {
6 const leftSq = nums[left] ** 2;
7 const rightSq = nums[right] ** 2;
8 if (leftSq > rightSq) {
9 result[pos] = leftSq;
10 left++;
11 } else {
12 result[pos] = rightSq;
13 right--;
14 }
15 pos--;
16 }
17 return result;
18}