Arrays Easy
Two Sum: Solution and Approach
Given an array of integers and a target, return the indices of the two numbers that add up to the target. Exactly one answer exists, and you can't use the same element twice.
Similar questions reported in: TCS, Infosys, Wipro, Amazon, Cognizant
Example
- Input:
- nums = [2, 7, 11, 15], target = 9
- Output:
- [0, 1]
Brute force first
Check every pair with two loops. This is O(n²) time.
The better idea
For each number x, the partner you need is target - x. Store each number you have already seen in a hash map (value → index). If the partner is already in the map, you have the answer.
Steps
- Create an empty map from value to index.
- Loop through the array. For each nums[i], compute need = target - nums[i].
- If need is in the map, return [map[need], i].
- Otherwise store nums[i] → i and continue.
Code
def two_sum(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], i]
seen[x] = i
return []public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>(); // value -> index
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (seen.containsKey(need)) {
return new int[] { seen.get(need), i };
}
seen.put(nums[i], i);
}
return new int[0];
}Complexity
Time: O(n): one pass, each map lookup is O(1) on average.
Space: O(n) for the map.
Edge cases to test
- Duplicates such as [3, 3] with target 6. Checking before inserting handles this.
- Negative numbers and zero work the same way.
Interview follow-up: If the array is sorted, solve it with two pointers in O(1) extra space.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.