Skip to content

Instantly share code, notes, and snippets.

@hassam-saeed
Created November 16, 2023 19:44
Show Gist options
  • Save hassam-saeed/91b3fe3d6a8fc4f1bf126ee77c2175a7 to your computer and use it in GitHub Desktop.
Save hassam-saeed/91b3fe3d6a8fc4f1bf126ee77c2175a7 to your computer and use it in GitHub Desktop.
A function to return indices of the elements that sums equal to the target number
function foo(nums, target) {
const indices = {};
for (let i = 0; i < nums.length; i++) {
const rem = target - nums[i];
if (indices[rem] !== undefined) return [indices[rem], i];
indices[nums[i]] = i;
}
}
# Time complexity: O(n)
foo([2,3,4], 6) => [0,2]
foo([3,2,4], 6) => [1,2]
foo([3,4,11,15], 7) => [0,1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment