“Squares of a Sorted Array” Ruby Solution Cheat Sheet.

The Squares of a Sorted Array List is in the easy category and is a good start for understanding more challenging algorithms using arrays as a data structure. I will focus on explaining a solution that works and not on the O time and space complexity.

Challenge: “Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.”LeetCode.




Create a new empty array. Loop through the original array, square each element. Push the squared elements into the new array, then return a new sorted array from smaller to greater.

1.Create a new array(non destructive )

new_array = []

2.Loop through the original array

nums.each do |number|

3. Square each element


4.Push the squared number to the new array

new_array << number**2

5.Return sorted array using sort method

new_array.sort{ |a,b| a <=> b}




Lifelong learner , Full Stack Software Engineer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store