Ranking Top Actors Across Shared Entity IDs
Medium · Data Manipulation (SQL/Python) · Software Engineer · Onsite
Problem Statement
Implement top_10_popular_actors(objects, credits) to rank the ten actors who have acted in the largest number of distinct films across a unified catalog.
Both films and individuals are stored together in a single objects collection sharing one object_id keyspace:
objects— entity dictionaries with keys:object_id(int): unique identifier across the entire catalog.object_type(str):'movie'or'person'.name(str): film title or person's display name.
credits— billing dictionaries with keys:movie_object_id(int): target film identifier.person_object_id(int): target person identifier.role(Optional[str]): billing label such as'actor','director','writer', orNone.
Catalog data may contain unnormalized strings, duplicate rows, and broken references, so apply all of the following rules:
- Role normalization: A credit qualifies as an acting credit if and only if
roleis a string whose whitespace-trimmed, lowercase value equals'actor'(for example,'actor','Actor', and' ACTOR 'count, whereas'director','', andNonedo not). - Entity type verification: Keep a credit only when
movie_object_idexists inobjectswithobject_type == 'movie'andperson_object_idexists inobjectswithobject_type == 'person'. Drop credits referencing missing IDs or IDs of the wrongobject_type. - Distinct film count: A person's
movie_countequals the number of distinct validmovie_object_ids on which they hold at least one valid acting credit. Multiple acting rows (or extra directing/writing rows) for the same(person_object_id, movie_object_id)pair still count that film only once. - Filtering and ranking: Exclude people with
0valid acting films. Sort qualifying actors bymovie_countdescending, breaking ties byperson_object_idascending (numeric order), and return at most the first10records as dictionaries with keysperson_object_id,name, andmovie_count.
Examples
Example 1
Input:
objects = [
{"object_id": 10, "object_type": "movie", "name": "Harbor Light"},
{"object_id": 20, "object_type": "movie", "name": "Glass Orbit"},
{"object_id": 30, "object_type": "movie", "name": "Night Train"},
{"object_id": 501, "object_type": "person", "name": "Nora"},
{"object_id": 502, "object_type": "person", "name": "Owen"},
{"object_id": 503, "object_type": "person", "name": "Pia"},
]
credits = [
{"movie_object_id": 10, "person_object_id": 501, "role": "actor"},
{"movie_object_id": 10, "person_object_id": 501, "role": "director"},
{"movie_object_id": 10, "person_object_id": 501, "role": "actor"},
{"movie_object_id": 20, "person_object_id": 501, "role": "actor"},
{"movie_object_id": 30, "person_object_id": 502, "role": "actor"},
{"movie_object_id": 10, "person_object_id": 503, "role": "director"},
]
Output:
[
{"person_object_id": 501, "name": "Nora", "movie_count": 2},
{"person_object_id": 502, "name": "Owen", "movie_count": 1},
]
Explanation: Nora (501) has two 'actor' rows and one 'director' row on film 10 plus one 'actor' row on film 20, giving 2 distinct films ({10, 20}). Owen (502) acted in film 30 (1 film). Pia (503) only directed, so she is omitted.
Example 2
Input:
objects = [
{"object_id": 1, "object_type": "movie", "name": "Red Dune"},
{"object_id": 2, "object_type": "movie", "name": "Cold Peak"},
{"object_id": 40, "object_type": "person", "name": "Tariq"},
{"object_id": 8, "object_type": "person", "name": "Sana"},
{"object_id": 15, "object_type": "person", "name": "Vera"},
]
credits = [
{"movie_object_id": 1, "person_object_id": 40, "role": "ACTOR"},
{"movie_object_id": 2, "person_object_id": 40, "role": " Actor "},
{"movie_object_id": 1, "person_object_id": 8, "role": "actor"},
{"movie_object_id": 2, "person_object_id": 8, "role": "actor"},
{"movie_object_id": 1, "person_object_id": 15, "role": "writer"},
{"movie_object_id": 2, "person_object_id": 15, "role": None},
]
Output:
[
{"person_object_id": 8, "name": "Sana", "movie_count": 2},
{"person_object_id": 40, "name": "Tariq", "movie_count": 2},
]
Explanation: After trimming whitespace and case-folding, 'ACTOR' and ' Actor ' both count as 'actor'. Sana (8) and Tariq (40) tie at 2 films, so smaller person_object_id (8 < 40) places Sana first. Vera (15) has zero acting credits.
Example 3
Input:
objects = [
{"object_id": 50, "object_type": "movie", "name": "Silent Reef"},
{"object_id": 60, "object_type": "person", "name": "Leo"},
]
credits = [
{"movie_object_id": 50, "person_object_id": 60, "role": "actor"},
{"movie_object_id": 404, "person_object_id": 60, "role": "actor"},
{"movie_object_id": 50, "person_object_id": 50, "role": "actor"},
{"movie_object_id": 60, "person_object_id": 60, "role": "actor"},
]
Output:
[{"person_object_id": 60, "name": "Leo", "movie_count": 1}]
Explanation: Only (50, 60, 'actor') links a 'movie' to a 'person'. ID 404 does not exist in objects, (50, 50) places a 'movie' ID in person_object_id, and (60, 60) places a 'person' ID in movie_object_id.
Constraints
0 <= len(objects) <= 10^50 <= len(credits) <= 2 * 10^5- Every
object_idinobjectsis a unique integer, andobject_typeis'movie'or'person'. roleincreditsis a string orNone.- If fewer than
10qualifying actors exist, return all of them in ranked order.
Step-by-step walkthrough
Pin down the rules and spot the data traps
We receive two collections—represented as relational tables in SQL or lists of dictionaries in Python:
objects:object_id,object_type('movie'or'person'), andname. Crucially, films and people share oneobject_idcatalog.credits:movie_object_id,person_object_id, androle. A person can appear in multiple rows for the same film (such as both'actor'and'director', or repeated'actor'rows).
Before writing code, confirm the four edge rules reflected in the specification and examples:
- Popularity metric:
movie_countequals the count of distinct valid films where a person holds at least one acting credit. People with zero qualifying acting credits are excluded. - Cutoff and tie-breaker: Return up to
10records sorted bymovie_countdescending, thenperson_object_idascending. (We also show the SQL variant that retains everyone tied at 10th place.) - Unnormalized role strings: Example 2 passes
'ACTOR',' Actor ','writer', andNone, counting'ACTOR'and' Actor 'as acting credits. Strip surrounding whitespace and lower-case strings before checking== 'actor'. - Dangling or wrong-type IDs: Example 3 includes a credit pointing to missing ID
404, a credit placing film50insideperson_object_id, and a credit placing person60insidemovie_object_id. Every endpoint must exist and match its expectedobject_type.
Why counting credit rows directly goes wrong
Two traps corrupt a naive
GROUP BY person_object_idaggregation:Trap 1 — Row inflation from multiple roles and repeated acting rows. Look at Example 1 (
Harbor Light=10,Glass Orbit=20,Night Train=30):Person Credits in input All rows Actor rows Distinct actor films -------- ------------------------------------------------- -------- ---------- -------------------- 501 Nora (10,actor), (10,director), (10,actor), (20,actor) 4 3 2 (films 10, 20) 502 Owen (30,actor) 1 1 1 (film 30) 503 Pia (10,director) 1 0 0 (excluded!)- Raw
COUNT(*)gives Nora4and includes Pia (1), who never acted in any film. - Filtering to
'actor'and runningCOUNT(*)still gives Nora3because(10, 501, 'actor')appears twice. - Filtering to valid acting rows first and taking
COUNT(DISTINCT movie_object_id)yields the true count of2.
Trap 2 — Shared
object_idkeyspace. Because films and people reside in oneobjectstable, an ID like50exists inobjects—as a'movie'!objects: [50, 'movie', 'Silent Reef'] [60, 'person', 'Leo'] bad credit A: movie_object_id = 404, person_object_id = 60 -> 404 missing from objects! bad credit B: movie_object_id = 50, person_object_id = 50 -> 50 exists, but 50 is 'movie', not 'person'! bad credit C: movie_object_id = 60, person_object_id = 60 -> 60 exists, but 60 is 'person', not 'movie'!Joining
creditstoobjectsonperson_object_idalone—or skippingobject_type—lets bad credit A count nonexistent film404and lets bad credit B rank'Silent Reef'as an actor! We must verify both endpoints againstobjectswithm.object_type = 'movie'andp.object_type = 'person'.- Raw
Write the SQL aggregation
Putting both safeguards into SQL produces a clean, single-query solution:
SELECT c.person_object_id, p.name, -- Count each valid film at most once per actor, even when actor rows repeat. COUNT(DISTINCT c.movie_object_id) AS movie_count FROM credits AS c -- Join 1: verify movie_object_id exists AND has object_type = 'movie'. JOIN objects AS m ON m.object_id = c.movie_object_id AND m.object_type = 'movie' -- Join 2: verify person_object_id exists AND has object_type = 'person' (and read name). JOIN objects AS p ON p.object_id = c.person_object_id AND p.object_type = 'person' -- Normalize whitespace and casing; NULL evaluates to UNKNOWN and is discarded. WHERE LOWER(TRIM(c.role)) = 'actor' GROUP BY c.person_object_id, p.name -- Deterministic tie-break by smaller person_object_id before slicing at 10. ORDER BY movie_count DESC, c.person_object_id ASC LIMIT 10;Build the Python lookup tables and per-actor film sets
In Python, we implement the exact same logic using dictionaries and sets:
- Scan
objectsonce to populatetype_ofandname_of. Callingtype_of.get(id)returnsNonefor missing IDs, so missing IDs and wrong-type IDs fail the exact same!= "movie"/!= "person"check. - For each credit whose normalized role equals
"actor"and whose endpoints pass both type checks, insertmovie_idintomovies_of[person_id]—asetthat automatically deduplicates repeatedmovie_ids.
def normalize_role(label: object) -> Optional[str]: """Trim whitespace and lower-case a role string like ' Actor '; non-strings return None.""" if not isinstance(label, str): return None return label.strip().lower() # Phase 1: Index objects by ID so we can verify each ID's type and look up person names in O(1) time. # Movies and people share the same object_id space, so every join must check object_type. # type_of: maps object_id -> 'movie' or 'person', e.g. {10: 'movie', 501: 'person'}. # name_of: maps object_id -> display name string, e.g. {10: 'Harbor Light', 501: 'Nora'}. type_of: Dict[object, object] = {} name_of: Dict[object, object] = {} for obj in objects: object_id = obj["object_id"] type_of[object_id] = obj["object_type"] name_of[object_id] = obj["name"] # Phase 2: Filter to valid actor credits and collect distinct movies per person. # movies_of: maps person_object_id -> set of distinct valid movie_object_ids, e.g. {501: {10, 20}}. # Using a set deduplicates repeated 'actor' rows for the same (person, movie) pair. movies_of: Dict[object, Set[object]] = {} for credit in credits: if normalize_role(credit.get("role")) != "actor": # Ignore non-actor roles ('director', 'writer') as well as None or blank roles. continue movie_id = credit["movie_object_id"] person_id = credit["person_object_id"] # Reject dangling IDs (type_of.get returns None) and swapped/wrong-type IDs. if type_of.get(movie_id) != "movie" or type_of.get(person_id) != "person": continue if person_id not in movies_of: movies_of[person_id] = set() movies_of[person_id].add(movie_id)- Scan
Sort, break ties, and handle tenth-place ties in SQL
We need
movie_countdescending andperson_object_idascending. Packing(-movie_count, person_id)tuples lets one ascendingranking.sort()order larger counts first (-3 < -2) while keepingperson_idsmallest-first (8 < 40):# Phase 3: Rank actors by movie_count descending, breaking ties by smaller person_object_id. # Negating movie_count lets Python's ascending tuple sort put largest counts first # while keeping person_object_id in ascending numeric order. ranking = [] for person_id, movie_set in movies_of.items(): movie_count = len(movie_set) ranking.append((-movie_count, person_id)) ranking.sort() # Slice the top 10 (or fewer if fewer than 10 valid actors exist) and format output rows. top: List[Dict[str, object]] = [] for negative_count, person_id in ranking[:10]: top.append({ "person_object_id": person_id, "name": name_of[person_id], "movie_count": -negative_count, })Variant — keeping everyone tied at 10th place:
LIMIT 10(andranking[:10]) truncates strictly at 10 rows. If asked to retain all actors tied with the 10th position, filter onRANK() OVER (ORDER BY movie_count DESC) <= 10(orFETCH FIRST 10 ROWS WITH TIESin standard SQL). ChooseRANK(), notDENSE_RANK():RANK()numbers ties1, 1, 3, ...soposition <= 10means "fewer than 10 actors strictly beat you," whereasDENSE_RANK() <= 10keeps the top 10 distinct count values, which can return hundreds of rows!WITH actor_counts AS ( SELECT c.person_object_id, p.name, COUNT(DISTINCT c.movie_object_id) AS movie_count FROM credits AS c JOIN objects AS m ON m.object_id = c.movie_object_id AND m.object_type = 'movie' JOIN objects AS p ON p.object_id = c.person_object_id AND p.object_type = 'person' WHERE LOWER(TRIM(c.role)) = 'actor' GROUP BY c.person_object_id, p.name ), ranked AS ( SELECT person_object_id, name, movie_count, RANK() OVER (ORDER BY movie_count DESC) AS position FROM actor_counts ) SELECT person_object_id, name, movie_count FROM ranked WHERE position <= 10 ORDER BY movie_count DESC, person_object_id ASC;Trace on Example 1 and Example 2
Tracing
top_10_popular_actorsacross Example 1 (Harbor Light10,Glass Orbit20,Night Train30;Nora501,Owen502,Pia503):Credit row Normalized role Type check (m, p) Action on movies_of --------------------- --------------- ------------------ --------------------------- (10, 501, 'actor') 'actor' ok movie, person ok movies_of[501] = {10} (10, 501, 'director') skip - unchanged (10, 501, 'actor') 'actor' ok movie, person ok movies_of[501] = {10} (dup) (20, 501, 'actor') 'actor' ok movie, person ok movies_of[501] = {10, 20} (30, 502, 'actor') 'actor' ok movie, person ok movies_of[502] = {30} (10, 503, 'director') skip - 503 never enters movies_of Sorted ranking tuples: [(-2, 501), (-1, 502)] Output: Nora (2), Owen (1)And in Example 2,
Tariq(40) gets{1, 2}from'ACTOR'and' Actor ',Sana(8) gets{1, 2}, and(-2, 8) < (-2, 40)ranksSanaahead ofTariq.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def normalize_role(label: object) -> Optional[str]: """Trim whitespace and lower-case a role string like ' Actor '; non-strings return None.""" if not isinstance(label, str): return None return label.strip().lower() def top_10_popular_actors(objects: List[Dict[str, object]], credits: List[Dict[str, object]]) -> List[Dict[str, object]]: # Phase 1: Index objects by ID so we can verify each ID's type and look up person names in O(1) time. # Movies and people share the same object_id space, so every join must check object_type. # type_of: maps object_id -> 'movie' or 'person', e.g. {10: 'movie', 501: 'person'}. # name_of: maps object_id -> display name string, e.g. {10: 'Harbor Light', 501: 'Nora'}. type_of: Dict[object, object] = {} name_of: Dict[object, object] = {} for obj in objects: object_id = obj["object_id"] type_of[object_id] = obj["object_type"] name_of[object_id] = obj["name"] # Phase 2: Filter to valid actor credits and collect distinct movies per person. # movies_of: maps person_object_id -> set of distinct valid movie_object_ids, e.g. {501: {10, 20}}. # Using a set deduplicates repeated 'actor' rows for the same (person, movie) pair. movies_of: Dict[object, Set[object]] = {} for credit in credits: if normalize_role(credit.get("role")) != "actor": # Ignore non-actor roles ('director', 'writer') as well as None or blank roles. continue movie_id = credit["movie_object_id"] person_id = credit["person_object_id"] # Reject dangling IDs (type_of.get returns None) and swapped/wrong-type IDs. if type_of.get(movie_id) != "movie" or type_of.get(person_id) != "person": continue if person_id not in movies_of: movies_of[person_id] = set() movies_of[person_id].add(movie_id) # Phase 3: Rank actors by movie_count descending, breaking ties by smaller person_object_id. # Negating movie_count lets Python's ascending tuple sort put largest counts first # while keeping person_object_id in ascending numeric order. ranking = [] for person_id, movie_set in movies_of.items(): movie_count = len(movie_set) ranking.append((-movie_count, person_id)) ranking.sort() # Slice the top 10 (or fewer if fewer than 10 valid actors exist) and format output rows. top: List[Dict[str, object]] = [] for negative_count, person_id in ranking[:10]: top.append({ "person_object_id": person_id, "name": name_of[person_id], "movie_count": -negative_count, }) return top✅ Submit now — all tests should pass.
Intuition & how it works
Imagine ranking prolific actors from a crate of end-credit slips where one performer can have multiple slips for the same movie (starring role, voice cameo, plus director) and where movies and performers share one master ID ledger. Rather than tallying raw slips, give each verified performer an envelope for unique film tokens: discard any slip whose normalized role is not 'actor', consult the ledger to verify that the film ID has type 'movie' and the performer ID has type 'person', and place the film token into that performer's envelope only if it is not already inside. Counting tokens per envelope yields each actor's true distinct film total.
Tallying raw credits rows fails because duplicate 'actor' rows and 'director' rows inflate counts—even ranking non-acting directors above working actors. Joining objects on just one column or skipping object_type checks also fails whenever referential integrity (the database guarantee that every foreign key points to an existing record of the intended entity type) is absent, allowing missing IDs or swapped entity types to pollute the leaderboard.
Walk through the traps from Examples 1 and 3:
1. Nora (object_id = 501, 'person') has two 'actor' rows and one 'director' row on film 10 plus one 'actor' row on film 20: the 'director' row is ignored, and her set {10, 20} counts 2 distinct films rather than 4 rows.
2. Credit (movie=404, person=60, role='actor') is dropped because 404 is absent from type_of.
3. Credit (movie=50, person=50, role='actor') where 50 has object_type = 'movie' is dropped because type_of.get(50) is 'movie', not 'person'.
Complexity
- Time: O(B + C + A log A), where
Bislen(objects),Cislen(credits), andAis the count of qualifying actors (A <= B). Indexingobjectsintotype_ofandname_ofvisitsBrecords inO(B)time, filteringcreditsperformsO(1)dictionary lookups and hash-set insertions acrossCrecords (O(C)), and sorting theA(-movie_count, person_id)tuples takesO(A log A)comparisons. - Space: O(B + P), where
P(P <= C) is the number of distinct valid(person_id, movie_id)pairs stored acrossmovies_of, alongsideO(B)entries intype_ofandname_of. - SQL scaling and indexing: With
objects.object_idas the primary key (the unique indexed identifier per row), both inner joins (joins keeping rows only when matching records exist on both sides) execute fast index probes. Normalizingroleat ingest time and adding a covering index (an index storing every queried column so the engine avoids reading base-table pages) on(role, person_object_id, movie_object_id)lets the database stream'actor'credits grouped by actor and film without sorting the full table.
Edge cases
- Fewer than 10 qualifying actors (including
0): Slicingranking[:10](andLIMIT 10in SQL) returns all available actors, or[]when no valid acting credits exist. - Multiple roles or duplicate
'actor'rows on one film: Non-actor roles are skipped up front, andmovies_of[person_id](set) collapses repeated(person_id, movie_id)pairs into1. - Messy or missing roles (
'ACTOR',' Actor ','',None):normalize_roletrims spaces and lower-cases strings while mapping non-strings toNone, matching Example 2. - Swapped or missing IDs: Requiring
type_of.get(movie_id) == 'movie'andtype_of.get(person_id) == 'person'rejects missing IDs (None) and wrong-type IDs alike. - Ties at or above the cutoff: Integer comparison inside
(-movie_count, person_id)orders tied actors numerically (8before40before100), never by string or input order. - Non-acting crew members: People holding only
'director'or'writer'rows never entermovies_of, so they never appear withmovie_count = 0.
Common mistakes
- Writing
COUNT(*)instead ofCOUNT(DISTINCT movie_object_id). Overcounts performers with multiple acting credits on the same film. - Forgetting to filter
rolebefore counting distinct films. Credits directors and writers with acting appearances. - Joining
objectsonly onperson_object_id. Leavesmovie_object_idunvalidated, letting nonexistent IDs like404or person IDs inflatemovie_count. - Joining
objectsonce viaON o.object_id IN (c.movie_object_id, c.person_object_id). Checks only one endpoint per joined row instead of verifying both endpoints simultaneously. - Checking
c.role = 'actor'without trimming and case-folding. Drops valid credits like'ACTOR'and' Actor 'in Example 2. - Using
DENSE_RANK() <= 10for 10th-place ties.DENSE_RANK()never skips numbers after ties, returning everyone with the top 10 distinct counts rather than top 10 actors plus ties at position 10 (RANK() <= 10).
Alternative approaches
- Bounded top-10 heap: Using
heapq.nsmallest(10, ranking)instead ofranking.sort()extracts the top 10 inO(A log 10)=O(A)time rather thanO(A log A). - Flat pair set plus counter: Insert valid
(person_id, movie_id)tuples into onesetand tallyperson_idfrequencies withcollections.Counter, mirroring a two-stage SQL CTE (common table expression: a named subquery defined withWITHto structure multi-step SQL).
Follow-up questions
- Suppose an actor's score is redefined as the sum of viewer interactions across every film they acted in. How would you write the query so duplicate actor rows do not multiply a film's interaction count? Joining raw
creditsdirectly to rawinteractionscauses a multiplicative fan-out: if Nora has two'actor'rows on Harbor Light and Harbor Light has500interactions, a direct join yields1,000rows for Nora. Avoid that fan-out with two pre-deduplicated CTEs—actor_moviesholdingSELECT DISTINCTvalid(person_object_id, name, movie_object_id)triples, andfilm_interactionspre-aggregated to one total permovie_object_id—joined viaLEFT JOINandCOALESCEso actors whose films have zero interactions still score0:
sql
WITH actor_movies AS (
SELECT DISTINCT c.person_object_id, p.name, c.movie_object_id
FROM credits AS c
JOIN objects AS m
ON m.object_id = c.movie_object_id AND m.object_type = 'movie'
JOIN objects AS p
ON p.object_id = c.person_object_id AND p.object_type = 'person'
WHERE LOWER(TRIM(c.role)) = 'actor'
),
film_interactions AS (
SELECT movie_object_id, COUNT(*) AS interaction_count
FROM interactions
GROUP BY movie_object_id
)
SELECT am.person_object_id,
am.name,
SUM(COALESCE(fi.interaction_count, 0)) AS score
FROM actor_movies AS am
LEFT JOIN film_interactions AS fi
ON fi.movie_object_id = am.movie_object_id
GROUP BY am.person_object_id, am.name
ORDER BY score DESC, am.person_object_id ASC
LIMIT 10;
- If the credit log contains billions of records and clients fetch this leaderboard constantly, how would you materialize and incrementally update the counts? Re-aggregating billions of credit rows on every request is prohibitive, so maintain two compact tables:
actor_film_links(person_object_id, movie_object_id, credit_row_count)with a unique key on(person_object_id, movie_object_id), andactor_film_totals(person_object_id, name, movie_count)indexed on(movie_count DESC, person_object_id ASC). When a validated acting credit arrives, incrementcredit_row_countinactor_film_linksand incrementmovie_countinactor_film_totalsonly whencredit_row_countrises from0to1(and on deletes, decrementmovie_countonly whencredit_row_countfalls from1to0). Leaderboard reads then scan just 10 index entries—or hit a short-TTL cache—while a periodic batch job verifies consistency. - How could a single SQL query return separate top-10 leaderboards for both actors and directors? Filter to
LOWER(TRIM(c.role)) IN ('actor', 'director'), group by the normalized role alongside(person_object_id, name)so people who both act and direct get an independent count per role, and rank within each role using a window function (a SQL calculation evaluated across a partition of rows without collapsing them) withPARTITION BY normalized_role:
sql
WITH role_counts AS (
SELECT LOWER(TRIM(c.role)) AS normalized_role,
c.person_object_id,
p.name,
COUNT(DISTINCT c.movie_object_id) AS movie_count
FROM credits AS c
JOIN objects AS m
ON m.object_id = c.movie_object_id AND m.object_type = 'movie'
JOIN objects AS p
ON p.object_id = c.person_object_id AND p.object_type = 'person'
WHERE LOWER(TRIM(c.role)) IN ('actor', 'director')
GROUP BY LOWER(TRIM(c.role)), c.person_object_id, p.name
),
ranked AS (
SELECT normalized_role, person_object_id, name, movie_count,
ROW_NUMBER() OVER (
PARTITION BY normalized_role
ORDER BY movie_count DESC, person_object_id ASC) AS rk
FROM role_counts
)
SELECT normalized_role AS role, rk AS position, person_object_id, name, movie_count
FROM ranked
WHERE rk <= 10
ORDER BY role ASC, position ASC;
Follow-up questions
- Suppose an actor's score is redefined as the sum of viewer interactions across every film they acted in. How would you write the query so duplicate actor rows do not multiply a film's interaction count?
- If the credit log contains billions of records and clients fetch this leaderboard constantly, how would you materialize and incrementally update the counts?
- How could a single SQL query return separate top-10 leaderboards for both actors and directors?
Similar questions
- Relational Document-Tag Schema and Multi-Tag SQL Queries
- Career Transition, Flagship Impact, Ambiguity, and Engineering Trade-offs
- Flexible-Schema Event Ingestion and Analytics Pipeline
- Resilient Event Ingestion with Strict Validation, Idempotency, and DLQ
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts