Similar Problems

Similar Problems not available

Number Of Students Unable To Eat Lunch - Leetcode Solution

Companies:

LeetCode:  Number Of Students Unable To Eat Lunch Leetcode Solution

Difficulty: Easy

Topics: stack array simulation  

Problem statement:

Given two integer arrays students and sandwiches. The value of students[i] is 1 if the ith student wants to eat a sandwich, and 0 otherwise. The value of sandwiches[j] is 1 if the jth sandwich is available, and 0 otherwise. Students are served sandwiches in the order they appear in the array.

Each student is waiting for exactly one sandwich. If there are no sandwiches available for a student, they may remain hungry indefinitely.

Return the number of students that are unable to eat lunch.

Solution:

One approach to solving this problem is by iterating through both arrays simultaneously and keeping track of the number of students unable to eat lunch. This can be done using a simple while loop and a counter variable.

The algorithm would be as follows:

  1. Initialize a counter variable to 0.
  2. Iterate through both arrays simultaneously using a while loop.
  3. If the current student wants a sandwich and there are sandwiches available, give them a sandwich and move to the next student.
  4. If the current student wants a sandwich but there are no sandwiches available, increment the counter variable and move to the next student.
  5. If the current student does not want a sandwich, move to the next student.
  6. If there are no more students or sandwiches left, break out of the loop and return the counter variable.

Here is the Python code for the solution:

def countStudents(students, sandwiches): counter = 0 i = 0 while i < len(students) and sandwiches: if students[i] == sandwiches[0]: sandwiches.pop(0) else: counter += 1 i += 1 return counter

The time complexity of this algorithm would be O(n), where n is the number of students. This is because we are iterating through both arrays only once.

The space complexity of this algorithm would be O(1), as we are not creating any new data structures.

In summary, the above algorithm provides a simple yet efficient solution to the Number Of Students Unable To Eat Lunch problem on leetcode.

Number Of Students Unable To Eat Lunch Solution Code

1