Last active
September 10, 2019 17:59
-
-
Save jaygiang/a7731239a4d86cb767660612dcbad399 to your computer and use it in GitHub Desktop.
Sum of Paired Indices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Write a function in JavaScript that accepts an array of integers and a number X as parameters, | |
// when invoked, returns an array of unique indices of two numbers whose sum is equal to X. | |
// For example: [1, 3, 4, 5, 6, 8, 10, 11, 13], Sum: 14 | |
// Pairs of indices: [0, 8], [1, 7], [2, 6], [4, 5] | |
const sumOfPairedIndices = (arr, sum) => { | |
const pairedIndices = []; | |
for (let i = 0; i < arr.length; i++){ | |
for (let j = i + 1; j < arr.length; j++){ | |
if (arr[i] + arr[j] === sum){ | |
pairedIndices.push([i, j]); | |
} | |
} | |
} | |
return pairedIndices; | |
} | |
sumOfPairedIndices([1, 3, 4, 5, 6, 8, 10, 11, 13], 14) | |
// function runs quadratic time O(n^2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment