#1700
Number of Students Unable to Eat Lunch
EasyArrayStackQueueSimulationQueueSimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of simulating the entire process, we can count how many students prefer each type of sandwich. If the number of students who prefer a type of sandwich exceeds the number of available sandwiches of that type, we can directly calculate how many students will be unable to eat.
⚙️
Algorithm
4 steps- 1Step 1: Count the number of students who prefer circular (0) and square (1) sandwiches.
- 2Step 2: For each sandwich type in the stack, decrement the respective count of students who prefer that type.
- 3Step 3: If a sandwich type is exhausted, check how many students are left who prefer that type.
- 4Step 4: The remaining students who cannot eat are those who still prefer a sandwich type that is no longer available.
solution.py9 lines
1def countStudents(students, sandwiches):
2 count = [0, 0]
3 for student in students:
4 count[student] += 1
5 for sandwich in sandwiches:
6 if count[sandwich] == 0:
7 break
8 count[sandwich] -= 1
9 return count[0] + count[1]ℹ
Complexity note: The time complexity is O(n) because we only traverse the students and sandwiches arrays once each, leading to linear time complexity.
- 1Understanding student preferences is crucial.
- 2Simulating the process can be inefficient; counting preferences is more effective.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.