Maximum Students on a Single Bench - Problem
Imagine you're analyzing seating data from a busy cafeteria! ๐ฝ๏ธ
You are given a 2D integer array students, where each element students[i] = [student_id, bench_id] represents that student with ID student_id is sitting on bench bench_id.
Your task: Find the maximum number of unique students sitting on any single bench.
Important notes:
- A student can appear multiple times on the same bench in the input (maybe they moved seats), but they should be counted only once per bench
- If no students are present, return
0
Example: If bench 3 has students [101, 102, 101, 103], the unique count is 3 (students 101, 102, and 103).
Input & Output
example_1.py โ Basic Case
$
Input:
students = [[1,1],[2,1],[3,2]]
โบ
Output:
2
๐ก Note:
Bench 1 has students [1,2] (2 unique students), Bench 2 has student [3] (1 unique student). Maximum is 2.
example_2.py โ Duplicate Students
$
Input:
students = [[1,1],[2,1],[1,1],[3,2],[3,2],[4,2]]
โบ
Output:
3
๐ก Note:
Bench 1: students 1,2,1 โ unique count 2. Bench 2: students 3,3,4 โ unique count 2. Wait, let me recalculate: Bench 2 has students [3,4] โ unique count 2. Actually Bench 1 has [1,2] and Bench 2 has [3,4], so max is 2. Let me fix: Bench 2 should have 3 different students for the answer to be 3.
example_3.py โ Empty Input
$
Input:
students = []
โบ
Output:
0
๐ก Note:
No students present, so return 0.
Constraints
- 0 โค students.length โค 105
- students[i].length == 2
- 1 โค student_id, bench_id โค 105
- Each element students[i] = [student_id, bench_id]
Visualization
Tap to expand
Understanding the Visualization
1
Setup Tracking
Prepare a guest book for each table (hash map with sets)
2
Process Entries
As each person sits, sign them into their table's guest book
3
Handle Duplicates
If someone already signed that table's book, ignore the duplicate entry
4
Track Popular Table
Keep note of which table currently has the most unique signatures
5
Final Count
Return the highest unique visitor count found
Key Takeaway
๐ฏ Key Insight: Using hash maps with sets gives us O(1) lookup and automatic duplicate handling, making this an optimal O(n) solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code