A solution to LeetCode Problem 977. Squares of a Sorted Array in JavaScript
If you’re preparing for technical interviews or want to improve your coding skills, solving practice problems on LeetCode is a great way.
In this post, we’ll discuss a solution to the “Squares of a Sorted Array” problem on LeetCode.
Problem Statements:
Given an integer array
nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.Example 1:
Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100].
Example 2:
Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
is sorted in non-decreasing order.
Solution
To solve this problem in JavaScript, we can use the built-in .sort() method to sort the array of squares. But first, we need to generate the array of squares.
To generate the array of squares, we can use the .map() method to iterate through the original array and return the square of each element. The .map() method takes a callback function as an argument, and this callback function should take in an element of the array as an argument and return the square of that element.
Once we have the array of squares, we can use the .sort() method to sort the array. The .sort() method takes a callback function as an argument, which specifies how to compare two elements in the array. For this problem, we want to sort the array in ascending order, so we can specify a callback function that compares the two elements and returns -1 if the first element is less than the second element, 1 if the first element is greater than the second element, and 0 if the two elements are equal.
Here is the complete solution in JavaScript:
const sortedSquares = (A) => {
return A.map((element) => element * element).sort((a, b) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
};
This solution has a time complexity of O(n * log n), as the .map() method has a time complexity of O(n) and the .sort() method has a time complexity of O(n * log n).
I hope this solution helps you understand how to solve Leetcode 977. Squares of a Sorted Array in JavaScript. Happy coding!