Coding Interview Prep: The Sorted Squared Array problem.

Moeedlodhi
1 min readNov 13, 2023

Let’s get on with this one.

Create a function that accepts a non-empty array of integers sorted in ascending order. The function should produce a new array, of equal length, containing the squares of the original integers while maintaining ascending order.

Sample Input:

[1, 2, 3, 5, 6, 8, 9]

Sample Output:

[1, 4, 25, 36, 64, 81]

Seems like a pretty simple problem. We are given an array that has been sorted in ascending order, and we have to return an array that contains the square of each element, also sorted in ascending order.

How I would do this one is by looping over the entire array and “squaring” each element then appending them to a list. Finally, I just sort my list and return the list. Simple.

Test cases to check your solution against:

test_cases =[{
"array": [1, 2, 3, 5, 6, 8, 9],
"expected_output" : [1, 4, 9, 25, 36, 64, 81]
},{
"array": [1]
"expected_output": [1]
},
{
"array": [1, 2],
"expected_output": [1, 4]
},{
"array": [1, 2, 3, 4, 5],
"expected_output": [1, 4, 9, 16, 25]
},{
"array": [-5, -4, -3, -2, -1]
"expected_output": [1, 4, 9, 16, 25]
}
]

My solution:

def sortedSquaredArray(array):
# Write your code here.
new_array = []
for number in array:
new_array.append(number**2)

return sorted(new_array)

This was a pretty simple problem, to be honest. Enjoyed reading this? Give it a like and share this for that helps me out truly. Till the next article

--

--