Two Sum
EasyGiven 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.
Examples
| Input | Output |
|---|---|
| nums = [2, 7, 11, 15], target = 9 | [0, 1] |
| nums = [3, 2, 4], target = 6 | [1, 2] |
Python Solution
def two_sum(nums: list[int], target: int) -> list[int]:
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []JavaScript Solution
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) {
return [seen.get(complement), i];
}
seen.set(nums[i], i);
}
return [];
}Step-by-Step Explanation
- Use a hash map to store each number and its index as we iterate.
- For each number, compute the complement (target - num).
- If the complement exists in the map, we've found our pair—return both indices.
- Otherwise, add the current number and its index to the map.
Complexity Analysis
| Time | O(n) |
| Space | O(n) |
Tags
ArrayHash Map
Related Problems
Related Tools
All Problems
Reverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix