Problem Solving with Go course

ComplexityChoosing a Data Structure

Problem Solving with Go

Display

Theme

Complexity · Output exercise

Choosing a Data Structure

Most speed decisions in puzzles aren't about clever tricks but about which data structure you use for the question asked most often. Ask yourself: which operation runs over and over?

Question asked oftenStructureCost per question
"is x there?"a set (map[T]struct{})O(1)
"how many times does x appear?"map[T]intO(1)
"what's element i?"a sliceO(1)
"sum from i to j?"a prefix sumO(1) after one O(n) pass
"is x there?" in a slicea loopO(n)
"what's the smallest value now?"a slice sorted againO(n log n) every time

The last row is a sign that a better structure exists, such as a heap, which comes in a later chapter.

Build once, ask many times

The pattern is nearly always the same: read the input, turn it into the right structure once, then answer every question from that structure. Checking q IDs against a slice of n visits takes n × q steps. Building a set takes n steps, then every check is constant: n + q in total.

A set gives you a bonus too: len(set) answers "how many different ones?" straight away.

Task

A library logs a visitor's card number every time someone comes in. The input has one visitors line with every visit (a card can come many times), then several check <number> lines.

For every check line, in order, print:

<number> yes

if that card has visited, or <number> no if it hasn't. At the end, print:

distinct visitors: <number of different cards>

Build a set once from the visits, then answer every check from it. The output must match the expected output exactly.

main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	var visitors []string // every visit, in order

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		fields := strings.Fields(scanner.Text())
		if len(fields) == 0 {
			continue
		}
		switch fields[0] {
		case "visitors":
			visitors = append(visitors, fields[1:]...)
		case "check":
			// TODO: print "<id> yes" or "<id> no", using a set built once,
			// not a loop over visitors for every check
		}
	}
	// TODO: this counts visits, not different visitors
	fmt.Println("distinct visitors:", len(visitors))
}
Go runtime not loaded yet

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