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
๐Ÿฝ๏ธ Cafeteria Table Popularity AnalysisTable 1๐Ÿ‘ฅ Alice, BobTable 2๐Ÿ‘ฅ Carol, DaveEveTable 3๐Ÿ‘ฅ FrankGuest Book 1โœ“ Alice (unique)โœ“ Bob (unique)โœ— Alice (duplicate)Count: 2Guest Book 2โœ“ Carol (unique)โœ“ Dave (unique)โœ“ Eve (unique)Count: 3 ๐Ÿ†Guest Book 3โœ“ Frank (unique)Count: 1๐Ÿ† Most PopularTable 2 with 3 unique visitorsHash maps with sets automatically handle duplicates!
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!
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 18
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen