From 330d32a8fbbdc7ef30d949cd14ca449364e5bfde Mon Sep 17 00:00:00 2001 From: mohit Date: Tue, 8 Oct 2024 01:23:02 +0530 Subject: [PATCH] added JS Problems --- Javascript/twoSum.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Javascript/twoSum.js diff --git a/Javascript/twoSum.js b/Javascript/twoSum.js new file mode 100644 index 0000000..4af8b89 --- /dev/null +++ b/Javascript/twoSum.js @@ -0,0 +1,19 @@ +// Two Sum Problem Solution in JavaScript +var twoSum = function(nums, target) { + const numMap = new Map(); // Create a hashmap to store the numbers and their indices + + for (let i = 0; i < nums.length; i++) { + const complement = target - nums[i]; // Find the complement + + if (numMap.has(complement)) { + return [numMap.get(complement), i]; // Return the indices if complement exists in the map + } + + numMap.set(nums[i], i); // Add the current number and its index to the map + } + + throw new Error("No two sum solution found!"); +}; + +// Example Usage: +console.log(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1]