Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding squares in sorted order in JavaScript
We are required to write a JavaScript function that takes in an array of integers, arr, sorted in increasing order.
Our function is supposed to return an array of the squares of each number, also sorted in increasing order.
For example, if the input to the function is ?
const arr = [-2, -1, 1, 3, 6, 8];
Then the output should be ?
const output = [1, 1, 4, 9, 36, 64];
The Challenge
Simply squaring and sorting would work, but it's inefficient. Since the original array is sorted, we can use a two-pointer approach to solve this in O(n) time.
Two-Pointer Approach
The key insight is that the largest square will always come from either the leftmost or rightmost element (since negative numbers become positive when squared).
const arr = [-2, -1, 1, 3, 6, 8];
const findSquares = (arr = []) => {
const res = []
let left = 0
let right = arr.length - 1
while (left <= right) {
const leftSquare = arr[left] * arr[left]
const rightSquare = arr[right] * arr[right]
if (leftSquare < rightSquare) {
res.push(rightSquare)
right -= 1
} else {
res.push(leftSquare)
left += 1
}
}
return res.reverse();
};
console.log(findSquares(arr));
[ 1, 1, 4, 9, 36, 64 ]
How It Works
The algorithm uses two pointers starting at opposite ends. At each step, it compares the squares of the elements at both pointers and adds the larger square to the result array. Since we're adding larger squares first, we reverse the array at the end to get ascending order.
Alternative: Simple Sort Method
For comparison, here's the straightforward approach:
const arr = [-2, -1, 1, 3, 6, 8];
const findSquaresSimple = (arr = []) => {
return arr.map(x => x * x).sort((a, b) => a - b);
};
console.log(findSquaresSimple(arr));
[ 1, 1, 4, 9, 36, 64 ]
Comparison
| Method | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| Two-Pointer | O(n) | O(n) | Optimal for sorted input |
| Square + Sort | O(n log n) | O(n) | Simpler but slower |
Conclusion
The two-pointer approach efficiently leverages the sorted nature of the input array to find squares in O(n) time. While the simple sort method is easier to understand, the two-pointer technique is optimal for this specific problem.
