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

Fadi Tillman
1 min readJul 10, 2021

The “Squares of a Sorted Array “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:

loop through the array, square each element then return a sorted array from smaller to greater.

1.Loop through the array

for (i= 0; i< nums.length;i++){}

2. Square each element using Math.pow(base, exponent)

nums[i] = Math.pow(nums[i], 2)

3.Return sorted array using sort method

return nums.sort((a,b) => a - b)

Solution:

var sortedSquares = function(nums) {for (i= 0; i < nums.length;i++){nums[i] = Math.pow(nums[i], 2)}return nums.sort((a,b) => a-b)};

--

--