Drill

ProblemsGo › payments

Charge each request only once

mediumpaymentsHash mapsArraysSimulationGo

The payment webhook is delivered at least once, sometimes more. Each delivery carries an idempotency key, and a replay must not charge the customer twice.

applyOnce(events: list<Event>) → 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 applyOnce(events []Event) int {
	
}

Worked examples

CallResult
applyOnce([]Event{Event{Key: "a", Amount: 100}, Event{Key: "b", Amount: 50}, Event{Key: "a", Amount: 100}})150
applyOnce([]Event{Event{Key: "a", Amount: 100}, Event{Key: "a", Amount: -100}})100
applyOnce([]Event{Event{Key: "x", Amount: 7}})7
applyOnce([]Event{})0

Hint

Remember the keys you have already honoured.

Reference solution in Go
func applyOnce(events []Event) int {
	seen := map[string]bool{}
	total := 0
	for _, e := range events {
		if seen[e.Key] {
			continue
		}
		seen[e.Key] = true
		total += e.Amount
	}
	return total
}

The same problem in another language

More payments problems in Go