Ranking Actors by Film Count in a Unified Object Database
SQL & DataAuto-graded · 19 test casesLast updated
Tests filtering credits by role, deduplicating person-movie pairs, validating object types in a shared ID space, and applying a deterministic tie-breaking policy.
You have a database where both movies and people share the same identifier space. Each object has a type indicating whether it represents a film or a person. Credits link people to movies through roles, and a single person may appear multiple times for the same movie with different roles—or even duplicate entries for the same role.
Your task is to identify the top actors by counting how many distinct films each person acted in. Only credits with the role 'actor' should count, regardless of case or surrounding whitespace.
You are given two lists representing database tables:
objects: Each entry contains:
object_id(int): unique identifier for either a movie or a personobject_type(str): either'movie'or'person'name(str): the title of the movie or the name of the person
credits: Each entry contains:
movie_object_id(int): references an object_id expected to be a movieperson_object_id(int): references an object_id expected to be a personrole(str or None): the role the person played, such as'actor'or'director'
Return the top 10 actors, where each actor is represented as a dictionary with:
person_object_id: the person's IDname: the person's namemovie_count: the number of distinct movies they acted in
Sort results by movie_count descending, then by person_object_id ascending. If there are fewer than 10 actors, return all of them.
Constraints
- The
rolefield may have inconsistent casing (e.g.,'Actor','actor') or extra whitespace (e.g.,' actor '). - The
rolefield may beNoneor a non-string type. - A person can have multiple credit entries for the same movie, including duplicates with the
'actor'role. - Credits may reference
object_idvalues that do not exist in the objects list, or may reference objects of the wrong type (e.g.,movie_object_idpointing to a person). - Only credits where both IDs reference valid objects of the correct type should be counted.
- Role comparison must be case-insensitive and ignore leading/trailing whitespace.
- An actor with zero valid acting credits should not appear in the results.
Examples
Example 1
Input: rank_actors_by_film_count([{'object_id': 1, 'object_type': 'movie', 'name': 'First Film'}, {'object_id': 2, 'object_type': 'movie', 'name': 'Second Film'}, {'object_id': 10, 'object_type': 'person', 'name': 'Alice'}, {'object_id': 20, 'object_type': 'person', 'name': 'Bob'}], [{'movie_object_id': 1, 'person_object_id': 10, 'role': 'actor'}, {'movie_object_id': 1, 'person_object_id': 10, 'role': 'director'}, {'movie_object_id': 1, 'person_object_id': 10, 'role': 'actor'}, {'movie_object_id': 2, 'person_object_id': 10, 'role': 'actor'}, {'movie_object_id': 1, 'person_object_id': 20, 'role': 'actor'}])
Output: [{'person_object_id': 10, 'name': 'Alice', 'movie_count': 2}, {'person_object_id': 20, 'name': 'Bob', 'movie_count': 1}]
Example 2
Input: rank_actors_by_film_count([{'object_id': 1, 'object_type': 'movie', 'name': 'A'}, {'object_id': 2, 'object_type': 'movie', 'name': 'B'}, {'object_id': 3, 'object_type': 'movie', 'name': 'C'}, {'object_id': 11, 'object_type': 'person', 'name': 'P1'}, {'object_id': 12, 'object_type': 'person', 'name': 'P2'}, {'object_id': 13, 'object_type': 'person', 'name': 'P3'}], [{'movie_object_id': 1, 'person_object_id': 11, 'role': 'Actor'}, {'movie_object_id': 2, 'person_object_id': 11, 'role': ' actor '}, {'movie_object_id': 1, 'person_object_id': 12, 'role': 'actor'}, {'movie_object_id': 3, 'person_object_id': 12, 'role': 'actor'}, {'movie_object_id': 1, 'person_object_id': 13, 'role': 'director'}, {'movie_object_id': 2, 'person_object_id': 13, 'role': None}])
Output: [{'person_object_id': 11, 'name': 'P1', 'movie_count': 2}, {'person_object_id': 12, 'name': 'P2', 'movie_count': 2}]
Example 3
Input: rank_actors_by_film_count([{'object_id': 7, 'object_type': 'movie', 'name': 'Only Movie'}, {'object_id': 9, 'object_type': 'person', 'name': 'Only Actor'}], [{'movie_object_id': 7, 'person_object_id': 9, 'role': 'actor'}, {'movie_object_id': 7, 'person_object_id': 9, 'role': 'actor'}, {'movie_object_id': 999, 'person_object_id': 9, 'role': 'actor'}, {'movie_object_id': 7, 'person_object_id': 7, 'role': 'actor'}])
Output: [{'person_object_id': 9, 'name': 'Only Actor', 'movie_count': 1}]
Hints
Hint 1
Consider how multiple credit rows for the same person and movie should be handled to avoid inflating the count.
Hint 2
Validate that movie_object_id actually points to a movie and person_object_id actually points to a person before counting.
Hint 3
Normalize the role string by stripping whitespace and converting to lowercase before comparing to 'actor'.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is accurately counting distinct films per actor while handling several data quality issues:
-
Build lookup tables: First, index all objects by their ID to quickly retrieve their type and name.
-
Filter and validate credits: For each credit entry:
- Check that the role is a string, strip whitespace, convert to lowercase, and compare against
'actor' - Verify that
movie_object_idreferences an object of type'movie' - Verify that
person_object_idreferences an object of type'person' - Skip any credits that fail these checks
- Check that the role is a string, strip whitespace, convert to lowercase, and compare against
-
Deduplicate per person: Use a set to track distinct movie IDs for each person. This automatically handles duplicate credit rows where the same person has multiple
'actor'entries for the same film, or holds both acting and non-acting roles. -
Aggregate and sort: Convert the person-to-films mapping into result dictionaries containing the person ID, name, and count of distinct films. Sort by count descending (higher counts first), then by person ID ascending (deterministic tie-breaking), and take the first 10 entries.
This approach correctly handles mixed object types in a shared ID space, unnormalized role strings, duplicate credits, and referential integrity violations.
Time Complexity: O(N + C + A log A) where N is the number of objects, C is the number of credits, and A is the number of actors (at most C). Building lookups is O(N), filtering credits is O(C), and sorting actors is O(A log A).
Space Complexity: O(N + A·M) where M is the average number of distinct films per actor. We store lookup tables for all objects and sets of film IDs for each actor.
from typing import List, Dict
from collections import defaultdict
def rank_actors_by_film_count(objects: List[Dict[str, object]], credits: List[Dict[str, object]]) -> List[Dict[str, object]]:
object_types = {}
object_names = {}
for obj in objects:
object_id = obj.get("object_id")
object_types[object_id] = obj.get("object_type")
object_names[object_id] = obj.get("name")
actor_films = defaultdict(set)
for credit in credits:
role = credit.get("role")
if not isinstance(role, str) or role.strip().lower() != "actor":
continue
movie_id = credit.get("movie_object_id")
person_id = credit.get("person_object_id")
if object_types.get(movie_id) != "movie":
continue
if object_types.get(person_id) != "person":
continue
actor_films[person_id].add(movie_id)
results = []
for person_id, films in actor_films.items():
results.append({
"person_object_id": person_id,
"name": object_names[person_id],
"movie_count": len(films),
})
results.sort(key=lambda entry: (-entry["movie_count"], entry["person_object_id"]))
return results[:10]