Array of Increasing Squared Numbers
A week ago, I participated in a mock technical interview in JavaScript.
Given an array of numbers in increasing order, return a new array of the squared results also in increasing order.
Input:
[-8, -5, -2, 0, 3, 7, 10]
Output:
[0, 4, 9, 25, 49, 64, 100]
My first step was to create a function, sortedSquaredNumbers
. This function would have a for
loop that iterates through each index in the array, squares it, pushes the result into a new array, then returns that new array.
function sortedSquaredNumbers(array) { const squaredArray = [] for (let i = 0; i < array.length; i++) { const squared = array[i]**2 squaredArray.push(squared) } return squaredArray.sort(function(a, b){return a - b})}
Using a built-in sort method, I pass in a function to specify how I would like the array to be sorted. Otherwise, the output we receive would be[0, 100, 25, 4, 49, 64, 9]
. This is because the JavaScript sort()
method converts each element into a string and then sorts the strings by unicode.
That was short and sweet, right? However, there is one thing to note about sort()
.
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
So what if we were to receive an array that was much larger than our example? It would be best to create a custom sort method that would handle infinitely growing arrays. Do you think you’re up for the challenge?