-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsquaresOfASortedArray.js
More file actions
41 lines (30 loc) · 909 Bytes
/
squaresOfASortedArray.js
File metadata and controls
41 lines (30 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Write code to create a function that accepts an array of integers sorted in ascending (increasing) order and returns a new array containing the squares of each number in ascending order
var sortedSquares = function(arr) {
var result = new Array(arr.length);
var idx1 = 0;
var idx2 = arr.length - 1;
var idx3 = result.length - 1;
while (idx1 <= idx2) {
var left = arr[idx1];
var right = arr[idx2];
if (Math.abs(left) > Math.abs(right)) {
result[idx3] = left ** 2;
idx1++;
} else {
result[idx3] = right ** 2;
idx2--;
}
idx3--;
}
return result;
};
// Alternate solution (less efficient)
// var sortedSquares = function(arr) {
// var squares = arr.map(function(num) {
// return num ** 2;
// });
// var sortedSquares = squares.sort(function(a, b) {
// return a - b;
// });
// return sortedSquares;
// };