C++ | Beats 100% | O(N) | With Explanation! | Concise & Readable
\n\nclass Solution {\npublic:\n    int countStudents(vector<int>& students, vector<int>& sandwiches) {\n        int n = students.size();\n        int sqStudents
![image](https://assets.leetcode.com/users/images/963492b9-3b2c-4647-a893-68b4ef221a3b_1664177914.752335.png)\n```\nclass Solution {\npublic:\n    int countStudents(vector<int>& students, vector<int>& sandwiches) {\n        int n = students.size();\n        int sqStudents = 0, circStudents = 0;\n        // Count student preferences.\n        for (int i = 0; i < students.size(); i++) {\n            sqStudents += students[i];\n            circStudents += !students[i];\n        }\n\n        for (int i = 0; i < sandwiches.size(); i++) {\n            // The top sandwich is square, but only circle preference students remain.\n            if (sandwiches[i] && !sqStudents) return circStudents;\n            // The top sandwich is circle, but only square preference students remain.\n            if (!sandwiches[i] && !circStudents) return sqStudents;\n            // Hand square sandwich to a square preference student.\n            if (sandwiches[i]) sqStudents--;\n            // Hand circle sandwich to a circle preference student.\n            else circStudents--;\n        }\n\n        // All sandwiches have been given out.\n        return 0;\n    }\n};\n```\n\nThis can be written more concisely as:\n\n```\nclass Solution {\npublic:\n    int countStudents(vector<int>& students, vector<int>& sandwiches) {\n        int n = students.size();\n        vector<int> counts = {0, 0};\n        // Count student preferences.\n        for (int student : students) {\n            counts[student]++;\n        }\n\n        for (int sandwich : sandwiches) {\n            // The top sandwich is square, but only circle preference students remain.\n            // OR\n            // The top sandwich is circle, but only square preference students remain.\n            if (!counts[sandwich]) return counts[!sandwich];\n            // Hand square sandwich to a square preference student.\n            // OR\n            // Hand circle sandwich to a circle preference student.\n            else counts[sandwich]--;\n        }\n\n        // All sandwiches have been given out.\n        return 0;\n    }\n};\n```\n\nIf you found this useful, an upvote would be greatly appreciated! Feedback is also welcomed :)
[]