3450. Maximum Students on a Single Bench 🔒
Problem Description
You are given a 2D integer array of student data students
, where students[i] = [student_id, bench_id]
represents that student student_id
is sitting on the 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.
Intuition
To solve this problem, the key is to keep track of which students are sitting on which benches and ensure that each student is counted only once per bench.
-
Data Structure Choice: Use a hash table to map each
bench_id
to a set ofstudent_id
s. This way, we can easily ensure that each student is counted uniquely for each bench, as sets automatically handle duplicate entries. -
Processing the Data: Iterate over the list of student-bench pairs. For each pair, add the student ID to the set associated with the corresponding bench ID in the hash table. This allows us to collect all unique students sitting on each bench.
-
Calculating the Result: After populating the hash table, the task is to find the bench with the maximum number of unique students. This can be achieved by checking the size of each set in the hash table and returning the largest size found.
Using these steps ensures that the solution is both efficient and accurate, leveraging data structures that naturally align with the problem's requirements.
Solution Approach
To implement the solution, we'll follow a structured approach using a hash table, as described in the reference solution.
-
Check for Empty List: Start by checking if the
students
list is empty. If it is, return 0 immediately, as there are no students present. -
Initialize the Hash Table: Use a
defaultdict
from thecollections
module, where each key is abench_id
and its value is a set. The set will store the uniquestudent_id
s for that bench. -
Populate the Hash Table: Iterate over each
student
entry in thestudents
list. For each[student_id, bench_id]
, add thestudent_id
to the set associated with the correspondingbench_id
in the hash table. By using a set, we automatically handle duplicate entries, ensuring each student is counted only once per bench. -
Determine the Maximum: Once the hash table is populated, calculate the maximum number of unique students sitting on any single bench. This can be done by finding the length of the largest set in the hash table, which can be efficiently achieved by using the
max
function withmap(len, d.values())
.
The code implementing this logic is as follows:
class Solution:
def maxStudentsOnBench(self, students: List[List[int]]) -> int:
if not students:
return 0
d = defaultdict(set)
for student_id, bench_id in students:
d[bench_id].add(student_id)
return max(map(len, d.values()))
This solution efficiently solves the problem by leveraging the properties of hash tables and sets. It ensures that operations like counting unique students per bench and finding maximum values are both simple and efficient.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through an example to illustrate the solution approach.
Example Input
Suppose we have the following input list of students and benches:
students = [ [1, 101], [2, 101], [1, 102], [3, 101], [2, 102], [2, 101] ]
This example shows that:
- Student 1 is sitting on benches 101 and 102.
- Student 2 is sitting on benches 101 and 102.
- Student 3 is sitting on bench 101.
- Student 2 is listed twice on bench 101, but should only be counted once.
Step-by-Step Solution
-
Check for Empty List: Here, the
students
list is not empty, so we proceed with the initialization. -
Initialize the Hash Table: Create a
defaultdict
where each key corresponds to abench_id
, and the value is a set to store uniquestudent_id
s. -
Populate the Hash Table: Iterate over each pair in the
students
list.- For the pair
[1, 101]
, add student 1 to the set for bench 101:{101: {1}}
. - For the pair
[2, 101]
, add student 2 to the set for bench 101:{101: {1, 2}}
. - For the pair
[1, 102]
, add student 1 to the set for bench 102:{101: {1, 2}, 102: {1}}
. - For the pair
[3, 101]
, add student 3 to the set for bench 101:{101: {1, 2, 3}, 102: {1}}
. - For the pair
[2, 102]
, add student 2 to the set for bench 102:{101: {1, 2, 3}, 102: {1, 2}}
. - The duplicate entry
[2, 101]
does not change the set, as student 2 is already included:{101: {1, 2, 3}, 102: {1, 2}}
.
- For the pair
-
Determine the Maximum: Calculate the maximum number of unique students for any bench by checking the sizes of these sets. In this example, for bench 101 we have 3 unique students, and for bench 102 we have 2 unique students.
Thus, the maximum number of unique students sitting on any single bench is:
max(3, 2) = 3
Conclusion
The function would return 3
, meaning the maximum number of unique students on one bench is 3.
Solution Implementation
1from collections import defaultdict
2from typing import List
3
4class Solution:
5 def maxStudentsOnBench(self, students: List[List[int]]) -> int:
6 # Check if the input list of students is empty
7 if not students:
8 return 0
9
10 # Create a dictionary to map each bench_id to a set of student_ids sitting on it
11 bench_to_students = defaultdict(set)
12
13 # Iterate over the list of students and their respective bench_ids
14 for student_id, bench_id in students:
15 # Add the student_id to the set of students for the corresponding bench_id
16 bench_to_students[bench_id].add(student_id)
17
18 # Return the maximum number of students that can be seated on a single bench
19 # This is determined by finding the bench with the largest set of students
20 return max(map(len, bench_to_students.values()))
21
1import java.util.HashMap;
2import java.util.HashSet;
3import java.util.Map;
4import java.util.Set;
5
6class Solution {
7 public int maxStudentsOnBench(int[][] students) {
8 // Initialize a map to store benchId as key and a set of studentIds as value
9 Map<Integer, Set<Integer>> benchToStudentsMap = new HashMap<>();
10
11 // Loop through each pair of studentId and benchId from the students array
12 for (var studentBenchPair : students) {
13 int studentId = studentBenchPair[0];
14 int benchId = studentBenchPair[1];
15
16 // Add studentId to the set corresponding to the benchId
17 benchToStudentsMap
18 .computeIfAbsent(benchId, k -> new HashSet<>())
19 .add(studentId);
20 }
21
22 // Variable to keep track of the maximum number of students on a single bench
23 int maxStudents = 0;
24
25 // Iterate over the set of studentIds for each benchId
26 for (var studentSet : benchToStudentsMap.values()) {
27 // Update maxStudents to be the maximum size of any student set found
28 maxStudents = Math.max(maxStudents, studentSet.size());
29 }
30
31 return maxStudents;
32 }
33}
34
1class Solution {
2public:
3 int maxStudentsOnBench(vector<vector<int>>& students) {
4 // Create a map to associate each bench with a set of student IDs
5 unordered_map<int, unordered_set<int>> benchToStudentsMap;
6
7 // Loop through each student's record
8 for (const auto& student : students) {
9 int studentId = student[0]; // Extract the student ID
10 int benchId = student[1]; // Extract the bench ID
11
12 // Map the bench ID to the set of student IDs
13 benchToStudentsMap[benchId].insert(studentId);
14 }
15
16 int maxStudents = 0; // Variable to keep track of maximum students on a single bench
17
18 // Iterate over each bench in the map
19 for (const auto& entry : benchToStudentsMap) {
20 // Update the maximum with the size of the current bench's student set
21 maxStudents = max(maxStudents, static_cast<int>(entry.second.size()));
22 }
23
24 return maxStudents; // Return the maximum number of students on any bench
25 }
26};
27
1function maxStudentsOnBench(students: number[][]): number {
2 // Map to store benchId as the key and a set of studentIds as the value
3 const benchesMap: Map<number, Set<number>> = new Map();
4
5 // Iterate over each pair of studentId and benchId
6 for (const [studentId, benchId] of students) {
7 // If the benchId is not already in the map, initialize it with an empty Set
8 if (!benchesMap.has(benchId)) {
9 benchesMap.set(benchId, new Set());
10 }
11 // Add the studentId to the set associated with the benchId
12 benchesMap.get(benchId)?.add(studentId);
13 }
14
15 // Variable to store the maximum number of students on any bench
16 let maxStudents = 0;
17
18 // Iterate over each set of studentIds in the map
19 for (const studentSet of benchesMap.values()) {
20 // Update maxStudents with the larger value between current max and the current set size
21 maxStudents = Math.max(maxStudents, studentSet.size);
22 }
23
24 // Return the maximum number of students on a single bench
25 return maxStudents;
26}
27
Time and Space Complexity
The time complexity of the code is O(n)
, where n
is the number of elements in the students
list. This is because the code iterates over each student exactly once to populate the dictionary d
.
The space complexity of the code is also O(n)
, as the dictionary d
stores each student in a set, and in the worst case, each student is associated with a unique bench, resulting in O(n)
space used.
Learn more about how to find time and space complexity quickly.
What is the best way of checking if an element exists in an unsorted array once in terms of time complexity? Select the best that applies.
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!