The Silver Screen Summit
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
- Asked in
- Visa
Problem
We rank actors on our box-office leaderboard by the sum of earnings across every movie they appear in. Return the names of the top n actors, biggest totals first, with tied totals in alphabetical order.
Box office totals decide who makes the top of the marquee.
Example
Input:
movies = [{"actor":"Alice","earnings":5000000},{"actor":"Bob","earnings":3000000},{"actor":"Alice","earnings":2000000},{"actor":"Charlie","earnings":8000000}], n = 2Output:
["Charlie","Alice"]
Worked solution and explanation
Why this problem exists in real interviews
This tests dict-based aggregation and sorting by computed values, a pattern that mirrors GROUP BY + ORDER BY in SQL. It probes whether a candidate can accumulate totals and then extract the top N entries efficiently.
Break down the requirements
Step 1: Aggregate earnings by actor name
Iterate through movie records, accumulating each actor's total box office earnings in a dict.
Step 2: Sort by total descending, then by name
Order the per-actor totals by total descending, and give the sort a second key on the actor name so equal totals come out alphabetically. Leaning on stable sort and dict insertion order only looks right when the input happens to list tied actors alphabetically; feed it Evan before Diane and the tie flips.
Step 3: Return the top N actor names
Slice the sorted list to get the first N entries and extract just the names.
The solution
def top_box_office(movies: list[dict], n: int) -> list[str]:
totals = {}
for movie in movies:
actor = movie["actor"]
totals[actor] = totals.get(actor, 0) + movie["earnings"]
# Negate the total so one ascending sort gives biggest first, names A to Z on ties.
ranked = sorted(totals.items(), key=lambda item: (-item[1], item[0]))
top = ranked[:n]
return [actor for actor, _ in top]Common follow-up questions
- How would you handle ties at the Nth position? (Tests whether you include all tied actors or strictly limit to N.)
- What if movie records could have missing earnings fields? (Tests defensive access patterns with `.get()` or try/except.)
- How would you optimize if N is much smaller than the number of actors? (Tests knowledge of heap-based selection: `heapq.nlargest(n, ...)` avoids full sort.)