Skip to content

1700. Number of Students Unable to Eat Lunch 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int countStudents(vector<int>& students, vector<int>& sandwiches) {
    vector<int> count(2);

    for (const int student : students)
      ++count[student];

    for (int i = 0; i < sandwiches.size(); ++i) {
      if (count[sandwiches[i]] == 0)
        return sandwiches.size() - i;
      --count[sandwiches[i]];
    }

    return 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int countStudents(int[] students, int[] sandwiches) {
    int[] count = new int[2];

    for (final int student : students)
      ++count[student];

    for (int i = 0; i < sandwiches.length; ++i) {
      if (count[sandwiches[i]] == 0)
        return sandwiches.length - i;
      --count[sandwiches[i]];
    }

    return 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def countStudents(self, students: list[int], sandwiches: list[int]) -> int:
    count = collections.Counter(students)

    for i, sandwich in enumerate(sandwiches):
      if count[sandwich] == 0:
        return len(sandwiches) - i
      count[sandwich] -= 1

    return 0