Problem Description
Given a list of student bench assignments where each element is of the form [student_id, bench_id], determine the maximum number of unique students sitting on any bench. Note that a student may appear more than once on the same bench, but they should only be counted once. If the input list is empty, return 0.
Key Insights
- Use a dictionary/hash map where each key is a bench_id and the value is a set of unique student_ids.
- By utilizing a set, duplicate student entries for the same bench are automatically ignored.
- Iterate over the dictionary's values to compute the size (i.e., number of unique students) for each bench and determine the maximum.
- Handle the edge case when the input is empty by returning 0.
Space and Time Complexity
Time Complexity: O(n), where n is the number of student records. Space Complexity: O(n), since in the worst case every student record is unique and stored in the map.
Solution
We solve this problem by iterating through the list of student records and building a mapping from bench_id to a set of student_ids. This ensures each student is counted only once per bench. After constructing this map, we iterate over its values to find the bench with the maximum number of unique students.
Code Solutions
Below are code solutions with detailed line-by-line comments in Python, JavaScript, C++, and Java.