Problem Solving with Go course

Maps and SetsFinding Pairs with a Map

Problem Solving with Go

Display

Theme

Maps and Sets · Test exercise

Finding Pairs with a Map

Given a list of numbers, find two that add up to exactly a target. It's one of the best-known patterns in interview practice and in puzzles, and solving it teaches one big idea: trade memory for time.

The direct way: every pair

for i := 0; i < len(prices); i++ {
	for j := i + 1; j < len(prices); j++ {
		if prices[i]+prices[j] == budget {
			return i, j, true
		}
	}
}

It's correct, but with n numbers there are about n²/2 pairs. With 100,000 numbers, that's 5 billion checks.

The map way: one pass

When you're at the number p, its partner must be budget - p. So the question isn't "which number fits?" but "has budget - p shown up already?". A map answers that in constant time:

firstAt := make(map[int]int) // price → first index it appeared at
for j, p := range prices {
	if i, seen := firstAt[budget-p]; seen {
		return i, j, true
	}
	if _, seen := firstAt[p]; !seen {
		firstAt[p] = j
	}
}

Two things to watch:

  • Check first, store after. If p is stored before the check, a 50 with a target of 100 gets paired with itself.
  • Store only the first index. When the same price shows up again, don't overwrite it, so the pair you return always uses the earliest index.

Counting every pair

The same pattern can count how many pairs i < j fit. Store how many times each number has appeared so far. When you meet p, every earlier budget - p makes one new pair:

pairs += seen[budget-p]
seen[p]++

Task

You have a gift voucher that must be spent exactly on two different items. The pairForBudget code in the editor already uses the map approach. Read it first, then:

  1. Complete countPairs(prices []int, budget int) int: the number of index pairs i < j with prices[i] + prices[j] == budget, in one pass with a map. A number can appear more than once, and every index pair counts.

The tests check pairForBudget too. Keep its behaviour: the pair whose second item comes earliest, and for that second item, the earliest first item.

main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

// pairForBudget finds two different items whose prices add up to exactly budget.
// It returns their indexes i < j: the pair whose second item j comes earliest,
// and for that j the earliest i. ok is false when there is no such pair.
func pairForBudget(prices []int, budget int) (i, j int, ok bool) {
	firstAt := make(map[int]int) // price → first index it appeared at
	for j, p := range prices {
		if i, seen := firstAt[budget-p]; seen {
			return i, j, true
		}
		if _, seen := firstAt[p]; !seen {
			firstAt[p] = j
		}
	}
	return 0, 0, false
}

// countPairs counts the pairs i < j with prices[i] + prices[j] == budget.
func countPairs(prices []int, budget int) int {
	// TODO: one pass, counting how many times each price has been seen
	return 0
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	fields := strings.Fields(string(data))
	if len(fields) < 2 || fields[0] != "budget" {
		fmt.Println(`want "budget <n>" and then the prices`)
		return
	}
	budget, err := strconv.Atoi(fields[1])
	if err != nil {
		fmt.Println("bad budget:", err)
		return
	}
	var prices []int
	for _, f := range fields[2:] {
		p, err := strconv.Atoi(f)
		if err != nil {
			fmt.Println("bad price:", err)
			return
		}
		prices = append(prices, p)
	}
	if i, j, ok := pairForBudget(prices, budget); ok {
		fmt.Printf("items %d and %d: %d + %d\n", i, j, prices[i], prices[j])
	} else {
		fmt.Println("no pair fits the budget")
	}
	fmt.Println("pairs that fit:", countPairs(prices, budget))
}
Go runtime not loaded yet

2 lines · 62 B of the 1 MB limit. Submit always uses the lesson's own input.