Squares of a Sorted Array | JavaScript | LeetCode
Leetcode Array Problems | Arrays 101
Here is a solution for an array problem called "Squares of a Sorted Array" using JavaScript.
Problem: Given an integer array nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Now let us take a look at the constraints:
1 <= nums.length <= 10<sup>4</sup>
This means that the array nums
will have at least 1 element and at most 10,000 elements.
-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup>
Each element in the array nums
can be as small as -10,000 and as large as 10,000.
nums
is sorted in non-decreasing order.
The array nums
is already sorted in non-decreasing order, meaning each element is less than or equal to the next element.
Now let us see the solution (JavaScript)
var sortedSquares = function(nums) {
let finalArray = [];
nums.forEach(num => {
finalArray.push(num * num);
})
for( let i=0 ; i < finalArray.length ; i++) {
for ( let j=i+1; j < finalArray.length; j++) {
if (finalArray[i] > finalArray[j]) {
let temp = finalArray[i];
finalArray[i] = finalArray[j];
finalArray[j] = temp;
}
}
}
return finalArray;
};
Optimize this solution using ChatGPT
var sortedSquares = function(nums) {
let n = nums.length;
let finalArray = new Array(n);
let left = 0;
let right = n - 1;
let index = n - 1;
while (left <= right) {
let leftSquare = nums[left] * nums[left];
let rightSquare = nums[right] * nums[right];
if (leftSquare > rightSquare) {
finalArray[index] = leftSquare;
left++;
} else {
finalArray[index] = rightSquare;
right--;
}
index--;
}
return finalArray;
};
Here it says to use the Two-Pointer Technique. If you are not familiar with it here are a few resources to understand it better:
Here is the explanation for the above code:
finalArray
: An array to store the result.left
: Pointer starting from the beginning of the array.right
: Pointer starting from the end of the array.index
: Position in thefinalArray
where the next largest square should be placed.Compare the squares of the elements at
left
andright
pointers.Place the larger square at the current
index
infinalArray
.Move the corresponding pointer inward (
left++
orright--
).Decrement
index
to fill the next position infinalArray
.
By using the two-pointer technique, we avoid the inefficiencies of a nested loop and achieve an optimal solution with a time complexity of O(n)
.
In conclusion, always begin by tackling problems independently. After putting in your best effort, look for optimal solutions.