Algo-Sim › Arrays & Hashing
Two Sum
Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input
Return the indices of the two numbers that add up to the target, in one pass with a hash map.
Problem
Given an integer array nums and an integer target, return the indices of the two different elements whose values add up to target. Exactly one such pair exists, and you may not use the same element twice. The indices can be returned in any order.
Constraints
- 2 ≤ nums.length ≤ 10⁴
- -10⁹ ≤ nums[i], target ≤ 10⁹
- Exactly one valid answer exists
- Aim for better than O(n²)
Edge cases to test
- The same value twice:
[3, 3], target 6 - A number must not pair with itself:
[3, 2, 4], target 6 - Negatives and a negative target
Follow-up questions
- What if the array is already sorted?
- Two pointers from both ends, moving the side that makes the sum too small or too big: O(n) time, O(1) space (LC 167).
- What if you must return every pair, or there may be none?
- Keep counts in the map and emit a pair for each earlier match; return an empty result when no lookup hits. Still O(n) plus the output size.
- What if memory is tight?
- If you only need the values (not the original indices) and may reorder the array, sort it in place and use two pointers: O(n log n) time, O(1) extra space.
Solution
Java
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
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[] { -1, -1 };
}Python
def two_sum(nums, target):
seen = {}
for i in range(len(nums)):
need = target - nums[i]
if need in seen:
return [seen[need], i]
seen[nums[i]] = i
return [-1, -1]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
unordered_map<int, int> seen = {};
for (int i = 0; i < int(nums.size()); i++) {
int need = target - nums[i];
if (seen.count(need)) {
return vector<int>{seen[need], i};
}
seen[nums[i]] = i;
}
return vector<int>{-1, -1};
}
};
More Arrays & Hashing problems
- Contains Duplicate (Easy)
- Valid Anagram (Easy)
- Group Anagrams (Medium)
- Top K Frequent Elements (Medium)
- Encode and Decode Strings (Medium)
- Product of Array Except Self (Medium)
- Longest Consecutive Sequence (Medium)
- Majority Element (Easy)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Subarray Sum Equals K (Medium)
- Design HashMap (Easy)