

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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]
- Related Questions & Answers
- Finding three desired consecutive numbers in JavaScript
- Finding desired sum of elements in an array in JavaScript
- Finding first unique element in sorted array in JavaScript
- Finding the first unique element in a sorted array in JavaScript
- Finding smallest element in a sorted array which is rotated in JavaScript
- Finding squares in sorted order in JavaScript
- Insert a number into a sorted array of numbers JavaScript
- Finding even length numbers from an array in JavaScript
- Finding perfect numbers in JavaScript
- Finding missing element in an array of numbers in JavaScript
- Finding Lucky Numbers in a Matrix in JavaScript
- Finding tidy numbers - JavaScript
- Finding two golden numbers in JavaScript
- Finding Armstrong numbers in a given range in JavaScript
- Finding pandigital numbers using JavaScript
Advertisements