From 13911fe68bc4a487c6104d5ce43306adc64d739e Mon Sep 17 00:00:00 2001 From: Meet Patel Date: Sun, 2 Nov 2025 18:32:34 -0800 Subject: [PATCH] completed mock 2 --- twoSum.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 twoSum.ts diff --git a/twoSum.ts b/twoSum.ts new file mode 100644 index 00000000..5b9dac18 --- /dev/null +++ b/twoSum.ts @@ -0,0 +1,17 @@ +// Time Complexity: O(n) +// Space Complexity: O(n) +function twoSum(nums: number[], target: number): number[] { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + // check if the remaining needed for target already exist in the map + if (map.has(target - nums[i])) { + return [i, map.get(target - nums[i])]; + } + + if (!map.has(nums[i])) { + // store the current number and its index in the map + map.set(nums[i], i); + } + } +}