Problem

The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.

The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:

  • If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.
  • Otherwise, they will leave it and go to the queue’s end.

This continues until none of the queue students want to take the top sandwich and are thus unable to eat.

You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Input: students = [1,1,0,0], sandwiches = [0,1,0,1]
Output: 0Explanation:
- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].
- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].
- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].
- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].
- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].
Hence all students are able to eat.

Example 2

1
2
Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
Output: 3

Constraints

  • 1 <= students.length, sandwiches.length <= 100
  • students.length == sandwiches.length
  • sandwiches[i] is 0 or 1.
  • students[i] is 0 or 1.

Solution

Method 1 – Simulation with Queue

Intuition

We simulate the process as described: students form a queue and sandwiches are in a stack. If the student at the front wants the top sandwich, they take it; otherwise, they go to the end. If after a full pass no one takes the top sandwich, the process stops. This works because the constraints are small.

Approach

  1. Use a queue for students and a pointer for the sandwich stack.
  2. For each sandwich, try to serve students in order:
    • If the front student wants the top sandwich, both leave.
    • Otherwise, the student goes to the end of the queue.
    • If after a full pass (queue size) no one takes the sandwich, stop.
  3. The number of students left in the queue is the answer.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <queue>
class Solution {
public:
    int countStudents(vector<int>& students, vector<int>& sandwiches) {
        queue<int> q;
        for (int s : students) q.push(s);
        int i = 0, n = sandwiches.size(), cnt = 0;
        while (!q.empty() && cnt < q.size()) {
            if (q.front() == sandwiches[i]) {
                q.pop();
                ++i;
                cnt = 0;
            } else {
                q.push(q.front());
                q.pop();
                ++cnt;
            }
        }
        return q.size();
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func countStudents(students []int, sandwiches []int) int {
    n := len(students)
    q := make([]int, n)
    copy(q, students)
    i, cnt := 0, 0
    for len(q) > 0 && cnt < len(q) {
        if q[0] == sandwiches[i] {
            q = q[1:]
            i++
            cnt = 0
        } else {
            q = append(q[1:], q[0])
            cnt++
        }
    }
    return len(q)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import java.util.*;
class Solution {
    public int countStudents(int[] students, int[] sandwiches) {
        Queue<Integer> q = new LinkedList<>();
        for (int s : students) q.offer(s);
        int i = 0, cnt = 0;
        while (!q.isEmpty() && cnt < q.size()) {
            if (q.peek() == sandwiches[i]) {
                q.poll();
                i++;
                cnt = 0;
            } else {
                q.offer(q.poll());
                cnt++;
            }
        }
        return q.size();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import java.util.LinkedList
class Solution {
    fun countStudents(students: IntArray, sandwiches: IntArray): Int {
        val q: java.util.Queue<Int> = LinkedList()
        for (s in students) q.offer(s)
        var i = 0
        var cnt = 0
        while (q.isNotEmpty() && cnt < q.size) {
            if (q.peek() == sandwiches[i]) {
                q.poll()
                i++
                cnt = 0
            } else {
                q.offer(q.poll())
                cnt++
            }
        }
        return q.size
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from collections import deque
class Solution:
    def countStudents(self, students: list[int], sandwiches: list[int]) -> int:
        q = deque(students)
        i = cnt = 0
        while q and cnt < len(q):
            if q[0] == sandwiches[i]:
                q.popleft()
                i += 1
                cnt = 0
            else:
                q.append(q.popleft())
                cnt += 1
        return len(q)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use std::collections::VecDeque;
impl Solution {
    pub fn count_students(students: Vec<i32>, sandwiches: Vec<i32>) -> i32 {
        let mut q: VecDeque<i32> = students.into();
        let mut i = 0;
        let mut cnt = 0;
        while !q.is_empty() && cnt < q.len() {
            if q[0] == sandwiches[i] {
                q.pop_front();
                i += 1;
                cnt = 0;
            } else {
                let s = q.pop_front().unwrap();
                q.push_back(s);
                cnt += 1;
            }
        }
        q.len() as i32
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    countStudents(students: number[], sandwiches: number[]): number {
        let q = students.slice();
        let i = 0, cnt = 0;
        while (q.length > 0 && cnt < q.length) {
            if (q[0] === sandwiches[i]) {
                q.shift();
                i++;
                cnt = 0;
            } else {
                q.push(q.shift()!);
                cnt++;
            }
        }
        return q.length;
    }
}

Complexity

  • ⏰ Time complexity: O(n^2), where n is the number of students. In the worst case, each student can be moved to the end of the queue up to n times.
  • 🧺 Space complexity: O(n), for the queue used to simulate the process.