progress

~/problems / Arrays & hashing / Hash maps and counting

Coffee-shop loyalty stamps

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A coffee shop gives at most one stamp per customer per day. The till log is an unordered list of (day, customer) purchases.

Write free_coffee(log: list[tuple[int, str]], k: int) -> list[str] that returns the customers who visited on at least k different days, sorted alphabetically.

log = [(1, "ivy"), (1, "ivy"), (2, "raj"), (3, "ivy"), (1, "raj"), (2, "ivy")]
free_coffee(log, 3)   # ["ivy"]          ivy: days {1, 2, 3}; raj: days {1, 2}
free_coffee(log, 2)   # ["ivy", "raj"]
free_coffee([], 1)    # []
  • Up to 2 * 10^5 purchases; 1 <= k <= 10^5; names are lowercase words.
  • ⭐ Bonus: a speed test with 200,000 purchases earns a star in one pass (O(n)).
Show hint

map each customer to a set of days (defaultdict(set)); len of each set is the stamp count.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc