Two Sum with a map
Fast recall
Quick revision
Core answer
Hash-map lookup, one-pass reasoning, and Go slice syntax.
Storing the current value before checking, which can reuse the same element.
State why the complement is checked first and explain the duplicate-value case.
Interview-ready guide
Interview answer
I keep previously seen values and their indexes in a map. For each number I ask whether its complement is already present; if yes, I return the two indexes, otherwise I record the number and continue.
Two Sum with a map
Direct Answer
Scan the slice once while storing each value's index in a map. For the current value x, look for target-x before storing x; this gives O(n) time and O(n) space.
Deep Dive & Architecture
Scan the slice once while storing each value's index in a map.
For the current value x, look for target-x before storing x; this gives O(n) time and O(n) space.
For every number, the only partner that can reach the target is target minus number. A map turns that lookup into constant average time.
Storing the current value before checking, which can reuse the same element.
Code Example
func twoSum(nums []int, target int) []int {
seen := map[int]int{}
for i, n := range nums {
if j, ok := seen[target-n]; ok { return []int{j, i} }
seen[n] = i
}
return nil
}
Common Mistakes & Pitfalls
Storing the current value before checking, which can reuse the same element.
Check your understanding
Answer these without looking back at the article.
- When would you use Two Sum Go in a real project?
- How would you compare Two Sum Go with an alternative?
- What is a common mistake when using Two Sum Go?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.