Java Approach | 1ms solution | space and time complexity:O(n)
\n# Intuition\nThe queue will help us keep track of the order of the students, while the list will help us keep track of the sandwiches that are left to be serv
![Screenshot 2024-04-08 at 7.09.38\u202FPM.png](https://assets.leetcode.com/users/images/f34ccd0e-606f-43ae-817a-794b91715c42_1712583595.379801.png)\n# Intuition\nThe queue will help us keep track of the order of the students, while the list will help us keep track of the sandwiches that are left to be served.\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1-Create a queue and a list to store the students and sandwiches respectively.\n2-If the sandwich matches the student, remove the student from the queue and move on to the next sandwich.\n3-If the sandwich does not match the student, add the student back to the end of the queue and increment a counter to keep track of the number of times the student has been moved to the back of the queue.\n4-If the counter reaches the size of the queue, it means that none of the students in the queue can be served with the remaining sandwiches, so we can return the size of the queue as the answer.\nIf we have served all the sandwiches, we can return the size of the queue as the answer.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n\n- Time complexity:O(n), where n is the length of the sandwiches array.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n), where n is the length of the students array.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int countStudents(int[] students, int[] sandwiches) {\n        ArrayList<Integer> list = new ArrayList<>();  // store students array for working of Queue\n        for(int i:students)\n        {\n            list.add(i);\n        }\n        int i=0;\n        int lastServe = 0;\n        int sand,stud;\n        while(i<sandwiches.length && lastServe<list.size())\n        {\n            sand=sandwiches[i];\n            stud = list.get(0);\n            if(sand==stud)\n            {\n                i++;\n                list.remove(0);\n                lastServe=0;\n            }\n            else\n            {\n                list.add(stud);\n                list.remove(0);\n                lastServe++;\n\n            }\n        }\n        return list.size();\n        \n    }\n}\n```\n\n\n
['Java']