Finding squares in sorted order in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of integers, arr, sorted in increasing order.

Our function is supposed to return an array of the squares of each number, also sorted in increasing order.

For example, if the input to the function is −

const arr = [-2, -1, 1, 3, 6, 8];

Then the output should be −

const output = [1, 1, 4, 9, 36, 64];

Example

The code for this will be −

 Live Demo

const arr = [-2, -1, 1, 3, 6, 8];
const findSquares = (arr = []) => {
   const res = []
   let left = 0
   let right = arr.length - 1
   while (left <= right) {
      const leftSquare = arr[left] * arr[left]
      const rightSquare = arr[right] * arr[right]
      if (leftSquare < rightSquare) {
         res.push(rightSquare)
         right -= 1
      } else {
         res.push(leftSquare)
         left += 1
      }
   }
   return res.reverse();
};
console.log(findSquares(arr));

Output

And the output in the console will be −

[ 1, 1, 4, 9, 36, 64 ]

Updated on: 09-Apr-2021

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements