Question

Two Sum - Both End Traversal

by cmruser

JavaScript

const array = [1,2,3,4,5,6];
const target = 100;

function twoSum(a, x) {
	let start = 0;
  let end = a.length - 1;
  
  while(start < end) {
  	const sum = a[start] + a[end];
    
    if(sum < x) {
    	start++;
    } else if(sum > x) {
    	end--;
    } else {
      return a[start] + ',' + a[end];
    }
    
  }
  
  return null;
}

const result = twoSum(array, target);

console.log(result);