You are given two integer arrays students
and sandwiches
where:
students[i]
is the type of the i-th student’s preferred sandwich (0
– the student prefers square sandwiches, or 1
– the student prefers circular sandwiches).sandwiches[j]
is the type of the j-th sandwich in the stack (i.e., the j-th sandwich is the one on the top of the stack).The students
are standing in a queue. Each student can either take the sandwich on the top of the stack or refuse it and go to the end of the queue. This continues until none of the students want to take the top sandwich and are thus unable to eat lunch. You need to return the number of students that are unable to eat lunch.
students
and sandwiches
arrays?
0
and 1
are valid types.To solve this problem, we’ll follow these steps:
0
and 1
).sandwiches
stack, and for each sandwich, check if there are students available who prefer that type.def countStudents(students, sandwiches):
# Count the number of students who prefer each type of sandwich
student_count = [students.count(0), students.count(1)]
for sandwich in sandwiches:
# If there is no student preferring the current type of sandwich, break the loop.
if student_count[sandwich] == 0:
break
# Otherwise, serve the sandwich and reduce the count of the corresponding student type.
else:
student_count[sandwich] -= 1
# The remaining students are the ones who can't get their preferred sandwich
return sum(student_count)
# Example usage:
students = [1, 1, 0, 0]
sandwiches = [0, 1, 0, 1]
print(countStudents(students, sandwiches)) # Output: 0
0
s and 1
s in the students
list takes O(n)
time, where n
is the number of students.sandwiches
stack and updating the counts takes O(n)
time.Thus, the overall time complexity is O(n)
.
This solution efficiently handles the problem within the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?