Two Sum
Difficulty: EASYCategory: DSAFrequency: 139Asked On 2025-04-29
Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Solution
1var twoSum = function(nums, target) {
2 let map = new Map;
3 for (var i = 0; i < nums.length; i++) {
4 let complement = target - nums[i];
5 if (map.has(complement)) {
6 return [map.get(complement), i]
7 }
8 map.set(nums[i], i);
9 }
10}