Created
November 16, 2023 19:44
-
-
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
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
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