File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ Goal: return indices of the two numbers such that they add up to target
3+
4+ Plan:
5+ - create a hash map (dict) to store number -> index
6+ - loop through nums with index i
7+ - get currentNum = nums[i]
8+ - compute pairNum = target - currentNum
9+ - if pairNum exists in dict
10+ -> return [dict[pairNum], i]
11+ - otherwise store currentNum in dict with its index
12+ - if no pair is found, return [-1, -1]
13+
14+ space complexity: O(n)
15+ time complexity: O(n)
16+ */
17+
18+ var twoSum = function ( nums , target ) {
19+ const dict = { } ;
20+
21+ for ( let i = 0 ; i < nums . length ; i ++ ) {
22+ const currentNum = nums [ i ] ;
23+ const pairNum = target - currentNum ;
24+
25+ if ( typeof dict [ pairNum ] === 'number' ) {
26+ return [ dict [ pairNum ] , i ] ;
27+ } else {
28+ dict [ currentNum ] = i ;
29+ }
30+ }
31+
32+ return [ - 1 , - 1 ] ;
33+ } ;
You can’t perform that action at this time.
0 commit comments