Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created July 7, 2023 12:46
Show Gist options
  • Save Ifihan/e58cfd4262775fb2ab7e84169994af2b to your computer and use it in GitHub Desktop.
Save Ifihan/e58cfd4262775fb2ab7e84169994af2b to your computer and use it in GitHub Desktop.
Number of Students Unable to Eat Lunch

Number of Students Unable to Eat Lunch

Question on Leetcode - Easy

Approach

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 sandwicheswere 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.

Code

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]

Complexities

  • Time complexity: O(n)
  • Space complexity: O(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment