
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 ]
Advertisements