Finding desired numbers in a sorted array in JavaScript

JavascriptWeb DevelopmentFront End Technology

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]
raja
Published on 20-Jan-2021 06:38:58
Advertisements