From 0e1b8fa33e49b6dbe85d4fcce697601a07a80d73 Mon Sep 17 00:00:00 2001 From: Yoon Kim Date: Thu, 2 Jan 2025 15:39:40 -0800 Subject: [PATCH] two sum solution --- two-sum/yoonthecoder.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 two-sum/yoonthecoder.js diff --git a/two-sum/yoonthecoder.js b/two-sum/yoonthecoder.js new file mode 100644 index 000000000..f37002549 --- /dev/null +++ b/two-sum/yoonthecoder.js @@ -0,0 +1,14 @@ +var twoSum = function (nums, target) { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + const complement = target - nums[i]; + if (map.has(complement)) { + return [map.get(complement), i]; + } + map.set(nums[i], i); + } +}; + +// Time complexity: O(n) +// Space complexity: O(n) - hash map storage