The Two Sum problem is one of the most popular and frequently asked coding interview questions. It evaluates your ability to work with arrays and hash maps efficiently.
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to the 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.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Use two loops to try every pair of elements and check if their sum equals the target.
var twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
};
Time Complexity: O(nยฒ)
Space Complexity: O(1)
Use a hash map to store the value-to-index mapping of each number as you iterate. For every element num
, check if target - num
exists in the map.
var twoSum = function(nums, target) {
const map = new Map(); // value -> index
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);
}
return []; // fallback, though the problem guarantees one solution
};
Metric | Value |
---|---|
Time Complexity | O(n) |
Space Complexity | O(n) |
n
= number of elements in the array
We traverse the array once and use a hash map to store seen values
Input: nums = [3, 2, 4]
, target = 6
Iteration 1: i=0
, num=3
, complement=3
โ not found โ store 3 โ map = {3: 0}
Iteration 2: i=1
, num=2
, complement=4
โ not found โ store 2 โ map = {3: 0, 2: 1}
Iteration 3: i=2
, num=4
, complement=2
โ found! โ return [1, 2]
โ Array has negative numbers
โ Target is 0
โ Using same element twice is not allowed
โ Exactly one solution guaranteed
Use hash maps for fast lookup (O(1))
Avoid nested loops unless absolutely necessary
Handle edge cases in the beginning