Skip to content

Commit cb574a6

Browse files
committed
two sum solution
1 parent cf40e6a commit cb574a6

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

two-sum/nancyel.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* Time Complexity: O(n) (using a single pass with a hash map)
3+
* (If a nested loop was used, it would be O(n^2))
4+
*/
5+
function twoSum(nums: number[], target: number): number[] {
6+
const numAndIndex = new Map<number, number>();
7+
8+
for (let i = 0; i < nums.length; i++) {
9+
const diff = target - nums[i];
10+
11+
if (numAndIndex.has(diff)) {
12+
return [numAndIndex.get(diff)!, i];
13+
}
14+
15+
numAndIndex.set(nums[i], i);
16+
}
17+
18+
return [];
19+
}

0 commit comments

Comments
 (0)