Skip to content

Commit 196aae9

Browse files
committed
solve: Week 01 Two Sum
1 parent a17a2d0 commit 196aae9

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

two-sum/eunice-hong.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Finds two numbers in the array that add up to the target value.
3+
* Uses a hash map to store previously seen numbers for O(n) time complexity.
4+
*
5+
* @param nums - An array of integers.
6+
* @param target - The target sum.
7+
* @returns A tuple containing the indices of the two numbers.
8+
*
9+
* Time Complexity: O(n)
10+
* Space Complexity: O(n)
11+
*/
12+
function twoSum(nums: number[], target: number): number[] {
13+
const map = new Map<number, number>();
14+
15+
for (let i = 0; i < nums.length; i++) {
16+
const complement = target - nums[i];
17+
if (map.has(complement)) {
18+
return [map.get(complement)!, i];
19+
}
20+
map.set(nums[i], i);
21+
}
22+
23+
throw new Error("No solution found");
24+
}

0 commit comments

Comments
 (0)