Maximum Students on a Single Bench - Problem

You are given a 2D integer array students, where students[i] = [student_id, bench_id] represents that student student_id is sitting on bench bench_id.

Return the maximum number of unique students sitting on any single bench.

If no students are present, return 0.

Note: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.

Input & Output

Example 1 — Basic Case
$ Input: students = [[1,1],[2,1],[3,2],[1,1],[4,2],[5,3]]
Output: 2
💡 Note: Bench 1 has students {1, 2} (2 unique), Bench 2 has students {3, 4} (2 unique), Bench 3 has student {5} (1 unique). Maximum is 2.
Example 2 — Empty Array
$ Input: students = []
Output: 0
💡 Note: No students present, return 0.
Example 3 — All Same Bench
$ Input: students = [[1,5],[2,5],[3,5],[1,5]]
Output: 3
💡 Note: All students sit on bench 5. Unique students are {1, 2, 3}, so return 3.

Constraints

  • 0 ≤ students.length ≤ 105
  • students[i].length == 2
  • 1 ≤ student_id, bench_id ≤ 105

Visualization

Tap to expand
Maximum Students on a Single Bench INPUT students[i] = [student_id, bench_id] [1,1] [2,1] [3,2] [1,1] [4,2] [5,3] Bench Visualization: Bench 1: 1 2 1 (dup) Bench 2: 3 4 Bench 3: 5 Numbers = Student IDs Faded = Duplicate entry ALGORITHM STEPS 1 Create Hash Map bench_id --> Set(student_ids) 2 Iterate Array Add student to bench's set 3 Set Handles Duplicates [1,1] appears twice, counted once 4 Find Maximum Size Return max set size among benches Hash Map State: 1 --> {1, 2} size: 2 2 --> {3, 4} size: 2 3 --> {5} size: 1 max(2, 2, 1) = 2 FINAL RESULT Maximum unique students on any single bench: 2 Both Bench 1 and Bench 2 have 2 unique students each Summary: Bench 1: Students {1, 2} = 2 Bench 2: Students {3, 4} = 2 Bench 3: Students {5} = 1 OK - Output: 2 Key Insight: Using a HashMap with Sets automatically handles duplicate entries. The Set data structure ensures each student is counted only once per bench. Time Complexity: O(n), Space Complexity: O(n) TutorialsPoint - Maximum Students on a Single Bench | Hash Map Approach
Asked in
Google 15 Amazon 12 Facebook 8
12.5K Views
Medium Frequency
~8 min Avg. Time
256 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