Given an integer array sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Need to square each element and save it in a new array sorted. The tricky part is when the array has negative numbers. It is worth mentioning that the input array is sorted, we will use that to our advantage.
We went through each element and then at the end we sorted the array. This solution also works with unsorted arrays. Since we know that the input array is sorted. There is a more optimal solution.
To solve this problem, we need to iterate through the array once, that leads us to a time complexity of O(n). The input array is already sorted so it no extra complexity is accounted for.
The space complexity is O(n) as a new array needs to be created to store the squared values.
public int[] bruteForce(final int[] inputArray) { final var sortedSquareArray = new int[inputArray.length]; for(int i = 0;i<inputArray.length;i++) { sortedSquareArray[i] = (int) Math.pow(inputArray[i],2); } Arrays.sort(sortedSquareArray); return sortedSquareArray; }
No need to sort at the end, thus having better time complexity. The strategy here is to note:
public int[] optimal(final int[] inputArray) { final var sortedSquareArray = new int[inputArray.length]; var startIndex = 0; var endIndex = inputArray.length-1; for(int i = inputArray.length-1;i>=0;i--) { var sortedArrayElement = 0; if(Math.abs(inputArray[endIndex]) > Math.abs(inputArray[startIndex])) { sortedArrayElement = (int) Math.pow(inputArray[endIndex],2); endIndex--; } else { sortedArrayElement = (int) Math.pow(inputArray[startIndex],2); startIndex++; } sortedSquareArray[i] = sortedArrayElement; } return sortedSquareArray; }
Sometimes you need time away to sort things out in your head. It makes everything clearer
Jojo Moyes