Drill

ProblemsGo › warmup

Find the two that add up

mediumwarmupHash mapsArraysGo

A reconciliation tool looks for the two entries that together explain a difference.

pairSummingTo(values: list<int>, target: int) → list<int>

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func pairSummingTo(values []int, target int) []int {
	
}

Worked examples

CallResult
pairSummingTo([]int{2, 7, 11, 15}, 9)[]int{0, 1}
pairSummingTo([]int{3, 2, 4}, 6)[]int{1, 2}
pairSummingTo([]int{3, 3}, 6)[]int{0, 1}
pairSummingTo([]int{1, 2}, 99)[]int{}

Hint

Walk once, and for each value ask whether the number that would complete it has already gone by.

Reference solution in Go
func pairSummingTo(values []int, target int) []int {
	seen := map[int]int{}
	for j, v := range values {
		need := target - v
		if i, ok := seen[need]; ok {
			return []int{i, j}
		}
		if _, ok := seen[v]; !ok {
			seen[v] = j
		}
	}
	return []int{}
}

The same problem in another language

More warmup problems in Go