Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
The brute force approach is quite intuitive and simple and follows the below steps:
result
and initialize its length to be the same as the input array
result
array.result
array again (since input array can have negative integers as well, it might be the case the there are some negative integers and their squares will be positive, hence disturbing the sorted order).results
array.O(nlogn)
- To sort the array, where n is the number of integers in the given array.O(n)
- For the results array.To iterate over the array and compare greater / smaller values, we are going to initialize two
pointers, start
and end
.
results
and initialize with the length of the input array.start
and end
. Initialize start
to the start i.e. arr[0]
and end to the end - i.e. arr[length - 1]
k
and initialize it to the end of the array - This is to keep track of where to put the number in the resulting array. We will be inserting values into the array from the end.start
is less than end
, check if the ABSOLUTE value of start number is LESS than or EQUAL to ABSOLUTE value of end number. If that is the case, we can square
the end
number and push it to the end of the result
array, decrementing end (end--
) and k
(k--
).arr[start] > arr[end]
, we simply square and push the start element while decrement k
and start
to search for the next value.O(n)
- Since we are going to iterate over the array only once (at max)O(n)
- Because of the result array.This solution is based towards javascript implementation of the problem using map()
and sort()
. It is a Brute Force Solution (As discussed in the first solution) but with a simpler syntax (JS devs would agree).