Go
Junior (0–2 yrs)
Coding
Frequent
Go
arrays
maps
Two Sum
LeetCode
Two Sum in Go — return indices of two numbers that add up to a target
go-jun-005
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Log in to save progress.
Model answer
Use a map[int]int to store value-to-index mappings as we iterate. For each element, compute complement = target - nums[i] and check if it exists in the map. If yes, return [stored index, i]. If no, store nums[i] -> i and continue. O(n) time, O(n) space. Maps in Go are hash maps, so lookups are amortised O(1).
Code example
package main
import "fmt"
func twoSum(nums []int, target int) []int {
seen := make(map[int]int) // value -> index
for i, n := range nums {
complement := target - n
if j, ok := seen[complement]; ok {
return []int{j, i}
}
seen[n] = i
}
return nil // no solution
}
func main() {
fmt.Println(twoSum([]int{2, 7, 11, 15}, 9)) // [0 1]
fmt.Println(twoSum([]int{3, 2, 4}, 6)) // [1 2]
}
Follow-up
What would you change if the array were sorted and you needed O(1) space? (Two-pointer technique.)