← Questions

Top k lottery winners by spending

0
AmazonCodingLast asked Jan 2026

A coding interview question asked in Amazon's technical phone screen, last asked Jan 2026. It tests heap, sorting and hashing.

Each lottery entry records who bought tickets and how much they spent. A person can appear in many entries. Return the k people who spent the most in total, highest first.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • top_spenders(entries: list[tuple[str, int]], k: int) -> list[str] — entries holds (person, amount) pairs. Order by total spent, descending; break ties by name, ascending. If fewer than k people exist, return them all.

Example

entries = [("ana", 30), ("bo", 50), ("cy", 20), ("ana", 25), ("dee", 50)]
# totals: ana 55, bo 50, dee 50, cy 20
top_spenders(entries, 2)   ->  ["ana", "bo"]
top_spenders(entries, 3)   ->  ["ana", "bo", "dee"]     # bo and dee tie; bo comes first by name

Constraints

  • Up to 10^6 entries; amounts are positive integers; k >= 1.
  • Totals can exceed 32 bits.

Clarifying questions

  • How are ties broken? Should tied people at the cut-off all be included?
  • Are amounts always positive, or can refunds appear?
  • Is k small compared with the number of people?

What a strong answer covers

  • Aggregate totals in a hash map in one pass, then select the top k.
  • Selection choices and costs: full sort O(m log m) for m people; a min-heap of size k, O(m log k); quickselect, O(m) on average. A heap or quickselect needs the tie rule built into the comparison so the result is deterministic.
  • Edge cases: k larger than the number of people, ties at the boundary, very large totals.

Follow-ups

  • New purchases keep arriving and the top k must stay current. What structure do you keep?
  • Return everyone tied with the k-th person as well.
  • The entries do not fit on one machine.

Where it's asked

  • Amazon · Technical phone screen · Last asked Jan 202660 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

heap · sorting · hashing

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding