Two Sum
🎯 Difficulty: EASY
🔗 LeetCodeProblem Statement
Given an array of integers nums and an integer target, return the 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.
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Approach: One-Pass Hash Map
The brute force approach uses nested loops to check every pair, which takes time. The optimal approach uses a Hash Map to reduce the time complexity to .
As we iterate through the array, we can check if the complement of the current number (i.e., target - current_number) already exists in our Hash Map.
- Initialize an empty Hash Map
mapto store numbers as keys and their indices as values. - Iterate through the array
numsusing a standardforloop so you have access to the indexi. - For each number, calculate its
complement = target - nums[i]. - Check if the
complementexists in themap.- If it does, you’ve found the pair! Return an array containing the
map[complement](the stored index) andi(the current index). - If it does not, add the current number and its index to the
mapas a key-value pair (map[nums[i]] = i) so it can be found by subsequent numbers.
- If it does, you’ve found the pair! Return an array containing the
Solution
function twoSum(nums, target) {
const map = {};
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (complement in map) {
return [map[complement], i];
}
map[nums[i]] = i;
}
return []; // Should not be reached based on problem constraints
}
Complexity Analysis
- Time Complexity: where is the length of the array. We iterate through the array exactly once. Hash map lookups and insertions take time on average.
- Space Complexity: . In the worst-case scenario, we might need to store almost all elements in the hash map before finding a match.