Question on Leetcode - Easy
My first approach was to traverse through the student
array and compare with the sandwiches
array. If they're the same, pop the student. If it is not, remove and add to the end of the array. Continue like that until there are no matches left and then return with the length. I was left with an error, hmm. It was inacurrate. The sandwiches
were not accounted for.
Then the second approach was using a while loop and popping the students
and sandwiches
if they were the same. If they are not, I searched for the student in the sandwiches
array and pop and return the length. It worked but I got Time Limit Exceeded.
My final approach was to use a hashmap to store 0's and 1's. I first count the number of students with each preference using a dictionary. Then, I iterate over the sandwiches, checking if there are any students remaining with the same preference. If a student is found, I decrement the count. If not, I break out of the loop. Finally, I return the sum of the remaining students with preferences 0 and 1.
class Solution:
def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
student_count = {0: 0, 1: 0} # Count of students with each preference
for student in students:
student_count[student] += 1
for sandwich in sandwiches:
if student_count[sandwich] > 0:
student_count[sandwich] -= 1
else:
break
return student_count[0] + student_count[1]
- Time complexity: O(n)
- Space complexity: O(1)