-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo-sum.ts
More file actions
33 lines (31 loc) · 1.1 KB
/
Copy pathtwo-sum.ts
File metadata and controls
33 lines (31 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 1. Two Sum (Easy)
* Link: https://leetcode.com/problems/two-sum/
*
* Given an array of integers `nums` and an integer `target`, return the indices
* of the two numbers that add up to `target`. Exactly one solution exists and
* the same element may not be used twice.
*
* Example:
* Input: nums = [2, 7, 11, 15], target = 9
* Output: [0, 1] // nums[0] + nums[1] === 9
*
* Approach:
* Single pass with a hash map from value -> index. For each number we ask
* whether its complement (target - num) was already seen; if so we have the
* pair. This avoids the O(n^2) brute-force double loop.
*
* Time: O(n) — one pass, O(1) map operations.
* Space: O(n) — up to n entries stored in the map.
*/
export function twoSum(nums: number[], target: number): [number, number] {
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) {
return [seen.get(complement)!, i];
}
seen.set(nums[i], i);
}
throw new Error("No two sum solution exists for the given input.");
}