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

Fadi Tillman
1 min readJul 10, 2021

--

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.

Note:

//Array data structure//Input sorted array smaller to a greater element//Return square of each element sorted smaller to greater element.

Example:

nums = [-3,-2,0,4,10]return [0,4,9,16,100]

Explanation:

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

number**2

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}

Solution:

def sorted_squares(nums)new_array = []nums.each {|number| new_array << number**2}new_array.sort{ |a,b| a <=> b}end

--

--