Drill

ProblemsGo › inventory

Group stock by how soon it expires

mediuminventoryHash mapsArraysGo

A food depot dashboard puts every batch into one of four buckets so staff can see what to move first.

expiryBuckets(daysLeft: list<int>) → map<string, 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 expiryBuckets(daysLeft []int) map[string]int {
	
}

Worked examples

CallResult
expiryBuckets([]int{-1, 0, 7, 8, 30, 31, 400})map[string]int{"expired": 1, "week": 2, "month": 2, "later": 2}
expiryBuckets([]int{})map[string]int{"expired": 0, "week": 0, "month": 0, "later": 0}
expiryBuckets([]int{-5, -5, -5})map[string]int{"expired": 3, "week": 0, "month": 0, "later": 0}
expiryBuckets([]int{0})map[string]int{"expired": 0, "week": 1, "month": 0, "later": 0}

Hint

Seed the map with all four keys at zero first, then walk the list once.

Reference solution in Go
func expiryBuckets(daysLeft []int) map[string]int {
	out := map[string]int{"expired": 0, "week": 0, "month": 0, "later": 0}
	for _, d := range daysLeft {
		switch {
		case d < 0:
			out["expired"]++
		case d <= 7:
			out["week"]++
		case d <= 30:
			out["month"]++
		default:
			out["later"]++
		}
	}
	return out
}

The same problem in another language

More inventory problems in Go