- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 desired numbers in a sorted array in JavaScript
We have an array of integers which is sorted in the increasing order. We are required to write a JavaScript function that takes in one such array as the first argument and a target sum number as the second argument.
The function should find and return two such numbers from the array that when added gives the target sum. The condition for solving this problem is that we have to do this in linear time and using constant space.
Example
Following is the code −
const arr = [4, 6, 8, 9, 11, 12, 18, 21]; const num = 27; const findElements = (arr = [], target) => { let left = 0; let right = arr.length - 1; let res = []; while (left < right) { let leftElement = arr[left]; let rightElement = arr[right]; if (leftElement + rightElement === target) { res.push(arr[left]); res.push(arr[right]); break; } else if (leftElement + rightElement > target) { right--; } else { left++; } } return res; }; console.log(findElements(arr, num));
Output
Following is the console output −
[6, 21]
Advertisements