Skip to content

Commit a16e999

Browse files
Jeehay28Jeehay28
authored andcommitted
Add Two Sum solution in TypeScript
1 parent 75c02d9 commit a16e999

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

two-sum/Jeehay28.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Approach 2: HashMap (Using Map in TypeScript)
2+
// ⏳ Time Complexity: O(n) ✅ (Efficient for large inputs)
3+
// 💾 Space Complexity: O(n) ❌ (Extra memory used for Map)
4+
5+
function twoSum(nums: number[], target: number): number[] {
6+
7+
const indices = new Map<number, number>();
8+
9+
for (let i = 0; i < nums.length; i++) {
10+
11+
const temp = target - nums[i];
12+
if (indices.has(temp)) {
13+
// Ensure correct order
14+
return [indices.get(temp)!, i];
15+
// The exclamation mark (!) in indices.get(temp)! is a non-null assertion operator in TypeScript.
16+
}
17+
// If you return [i, indices.get(temp)!],
18+
// you would be returning the current index first,
19+
// which is incorrect because the problem statement usually expects indices in the order they were found (earlier index first).
20+
21+
indices.set(nums[i], i);
22+
}
23+
return [];
24+
};
25+
26+
27+
// Approach 1: Brute Force (O(n^2))
28+
// ⏳ Time Complexity: O(n^2) ❌ (Inefficient for large inputs)
29+
// 💾 Space Complexity: O(1) ✅ (Great, no extra memory used!)
30+
31+
// function twoSum(nums: number[], target: number): number[] {
32+
// for (let i = 0; i < nums.length; i++) {
33+
// for (let j = i + 1; j < nums.length; j++) {
34+
// if (nums[i] + nums[j] === target) {
35+
// return [i, j]
36+
// }
37+
// }
38+
// }
39+
// return [];
40+
// };
41+
42+

0 commit comments

Comments
 (0)