JSFiddle - React, Tailwind, and code Playground

by jacobwsmith

JavaScript

console.clear();

/* 
Given an array of numbers, return indices of the two integers such that they add up to a specific target.

You should assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given numbers = [2, 7, 11, 15], target = 9,

Because numbers[0] + numbers[1] = 2 + 7 = 9,
return [0, 1].
*/


let lowIndex = 0;

const findIndices = function(numbers, target) {
	let counter = numbers.length-1;
  let result = [];
  while (numbers[counter] > (target - numbers[0]) && target > 0) {
  	
    counter--;
  }
  numbers.length = counter+1;
	if (numbers[lowIndex] + numbers[counter] != target) {
  	lowIndex++;
    result = findIndices(numbers, target);
  }	else {
	  result = [lowIndex, counter];
  }
	return result;
};

const isArrayEqualHelper = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);

// Tests should return true 😊
console.log(isArrayEqualHelper(findIndices([2, 7, 11, 15], 9), [0, 1])); // [0, 1];
console.log(isArrayEqualHelper(findIndices([2, 7, 11, 15], 17), [0, 3])); // [0, 3];
console.log(isArrayEqualHelper(findIndices([1, 2, 3, 4, 5, 6, 7, 8, 9], 6), [0, 4])); // [ 1, 3] or [0, 4];
console.log(isArrayEqualHelper(findIndices([1, 2, 3, 4, 5, 6, 7, 8, 9], 10), [0, 8])); // [ 3, 5] or [0, 8];