-
-
Save QuocCao-dev/fae7141e7be9278de665bc25a82de73d to your computer and use it in GitHub Desktop.
const make_squares = function (arr: number[]) {
// TODO: Write your code here
return ;
};
make_squares([-2,-1,0,2,3]) // [0,1,4,4,9]
make_squares([-3,-1,0,1,2]) // [0,1,1,4,9]This is a straightforward question. The only trick is that we can have negative numbers in the input array, which will make it a bit difficult to generate the output array with squares in sorted order.
An easier approach could be to first find the index of the first non-negative number in the array. After that, we can use Two Pointers to iterate the array. One pointer will move forward to iterate the non-negative numbers, and the other pointer will move backward to iterate the negative numbers. At any step, whichever number gives us a bigger square will be added to the output array. For the above-mentioned Example-1, we will do something like this:

Since the numbers at both ends can give us the largest square, an alternate approach could be to use two pointers starting at both ends of the input array. At any step, whichever pointer gives us the bigger square, we add it to the result array and move to the next/previous number according to the pointer. For the above-mentioned Example-1, we will do something like this:




