Given a sorted list of integers, square the elements and give the output in sorted order.
For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81].
My solution 1:
const square = el => el * el;
const sortAsc = (a, b) => a - b;
const sortSquare = list => list
.map(square)
.sort(sortAsc);
console.log(sortSquare([-9, -2, 0, 2, 3]));
My solution 2:
const sortSquare2 = list => {
list.sort((a, b) => Math.abs(a) - Math.abs(b));
for (let i = 0; i < list.length; i++) {
list[i] = Math.pow(list[i], 2);
}
return list;
};
console.log(sortSquare2([-9, -2, 0, 2, 3]));
Is there a faster solution? I have the feeling you can do something with the fact that the list is sorted to begin with. But I can't think of a good one.