We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a17a2d0 commit 196aae9Copy full SHA for 196aae9
two-sum/eunice-hong.ts
@@ -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