Maximum Students Taking Exam
Time O(m * n * sqrt(m * n)) · Space O(m + n) · Official statement on LeetCode
Solutions
// Time: O(m * n * sqrt(m * n))
// Space: O(m * n)
// template from https://www.geeksforgeeks.org/hopcroft-karp-algorithm-for-maximum-matching-set-2-implementation/
static const int NIL = 0;
static const int INF = numeric_limits<int>::max();
// A class to represent Bipartite graph for Hopcroft
// Karp implementation
// Time: O(E * sqrt(V))
// Space: O(V)
class BipGraph
{
// m and n are number of vertices on left
// and right sides of Bipartite Graph
int m, n;
// adj[u] stores adjacents of left side
// vertex 'u'. The value of u ranges from 1 to m.
// 0 is used for dummy vertex
list<int> *adj;
// These are basically pointers to arrays needed
// for hopcroftKarp()
int *pairU, *pairV, *dist;
public:
BipGraph(int m, int n); // Constructor
void addEdge(int u, int v); // To add edge
// Returns true if there is an augmenting path
bool bfs();
// Adds augmenting path if there is one beginning
// with u
bool dfs(int u);
// Returns size of maximum matching
int hopcroftKarp();
};
// Returns size of maximum matching
int BipGraph::hopcroftKarp()
{
// pairU[u] stores pair of u in matching where u
// is a vertex on left side of Bipartite Graph.
// If u doesn't have any pair, then pairU[u] is NIL
pairU = new int[m+1];
// pairV[v] stores pair of v in matching. If v
// doesn't have any pair, then pairU[v] is NIL
pairV = new int[n+1];
// dist[u] stores distance of left side vertices
// dist[u] is one more than dist[u'] if u is next
// to u'in augmenting path
dist = new int[m+1];
// Initialize NIL as pair of all vertices
for (int u=0; u<=m; u++)
pairU[u] = NIL;
for (int v=0; v<=n; v++)
pairV[v] = NIL;
// Initialize result
int result = 0;
// Keep updating the result while there is an
// augmenting path.
while (bfs())
{
// Find a free vertex
for (int u=1; u<=m; u++)
// If current vertex is free and there is
// an augmenting path from current vertex
if (pairU[u]==NIL && dfs(u))
result++;
}
return result;
}
// Returns true if there is an augmenting path, else returns
// false
bool BipGraph::bfs()
{
queue<int> Q; //an integer queue
// First layer of vertices (set distance as 0)
for (int u=1; u<=m; u++)
{
// If this is a free vertex, add it to queue
if (pairU[u]==NIL)
{
// u is not matched
dist[u] = 0;
Q.push(u);
}
// Else set distance as infinite so that this vertex
// is considered next time
else dist[u] = INF;
}
// Initialize distance to NIL as infinite
dist[NIL] = INF;
// Q is going to contain vertices of left side only.
while (!Q.empty())
{
// Dequeue a vertex
int u = Q.front();
Q.pop();
// If this node is not NIL and can provide a shorter path to NIL
if (dist[u] < dist[NIL])
{
// Get all adjacent vertices of the dequeued vertex u
list<int>::iterator i;
for (i=adj[u].begin(); i!=adj[u].end(); ++i)
{
int v = *i;
// If pair of v is not considered so far
// (v, pairV[V]) is not yet explored edge.
if (dist[pairV[v]] == INF)
{
// Consider the pair and add it to queue
dist[pairV[v]] = dist[u] + 1;
Q.push(pairV[v]);
}
}
}
}
// If we could come back to NIL using alternating path of distinct
// vertices then there is an augmenting path
return (dist[NIL] != INF);
}
// Returns true if there is an augmenting path beginning with free vertex u
bool BipGraph::dfs(int u)
{
if (u != NIL)
{
list<int>::iterator i;
for (i=adj[u].begin(); i!=adj[u].end(); ++i)
{
// Adjacent to u
int v = *i;
// Follow the distances set by BFS
if (dist[pairV[v]] == dist[u]+1)
{
// If dfs for pair of v also returns
// true
if (dfs(pairV[v]) == true)
{
pairV[v] = u;
pairU[u] = v;
return true;
}
}
}
// If there is no augmenting path beginning with u.
dist[u] = INF;
return false;
}
return true;
}
// Constructor
BipGraph::BipGraph(int m, int n)
{
this->m = m;
this->n = n;
adj = new list<int>[m+1];
}
// To add edge from u to v and v to u
void BipGraph::addEdge(int u, int v)
{
adj[u].push_back(v); // Add u to v’s list.
}
// Hopcroft-Karp bipartite matching
class Solution {
public:
int maxStudents(vector<vector<char>>& seats) {
static vector<pair<int, int>> directions = {{-1, -1}, {0, -1}, {1, -1},
{-1, 1}, {0, 1}, {1, 1}};
unordered_map<int, int> lookup;
int u = 0, v = 0;
for (int i = 0; i < seats.size(); ++i) {
for (int j = 0; j < seats[0].size(); ++j) {
if (seats[i][j] != '.') {
continue;
}
lookup[i * seats[0].size() + j] = (j % 2 == 0) ? ++u : ++v;
}
}
BipGraph g(seats.size() * seats[0].size(), seats.size() * seats[0].size());
for (int i = 0; i < seats.size(); ++i) {
for (int j = 0; j < seats[0].size(); j += 2) {
if (seats[i][j] != '.') {
continue;
}
for (const auto& [dx, dy] : directions) {
const auto& [ni, nj] = make_pair(i + dx, j + dy);
if (0 <= ni && ni < seats.size() &&
0 <= nj && nj < seats[0].size() &&
seats[ni][nj] == '.') {
g.addEdge(lookup[i * seats[0].size() + j],
lookup[ni * seats[0].size() + nj]);
}
}
}
}
return u + v - g.hopcroftKarp();
}
};
// Time: O(|V| * |E|) = O(m^2 * n^2)
// Space: O(|V| + |E|) = O(m * n)
// Hungarian bipartite matching
class Solution2 {
public:
int maxStudents(vector<vector<char>>& seats) {
int count = 0;
for (int i = 0; i < seats.size(); ++i) {
for (int j = 0; j < seats[0].size(); ++j) {
if (seats[i][j] != '.') {
continue;
}
++count;
}
}
return count - Hungarian(seats);
}
private:
int Hungarian(const vector<vector<char>>& seats) {
int result = 0;
vector<vector<pair<int, int>>> matching(seats.size(),
vector<pair<int, int>>(seats[0].size(), {-1, -1}));
for (int i = 0; i < seats.size(); ++i) {
for (int j = 0; j < seats[0].size(); j += 2) {
if (seats[i][j] != '.') {
continue;
}
vector<vector<bool>> lookup(seats.size(),
vector<bool>(seats[0].size(), false));
if (dfs(seats, {i, j}, &lookup, &matching)) {
++result;
}
}
}
return result;
}
int dfs(const vector<vector<char>>& seats,
const pair<int, int>& e,
vector<vector<bool>> *lookup,
vector<vector<pair<int, int>>> *matching) {
static vector<pair<int, int>> directions = {{-1, -1}, {0, -1}, {1, -1},
{-1, 1}, {0, 1}, {1, 1}};
const auto& [i, j] = e;
for (const auto& [dx, dy] : directions) {
const auto& [ni, nj] = make_pair(i + dx, j + dy);
if (0 <= ni && ni < seats.size() &&
0 <= nj && nj < seats[0].size() &&
seats[ni][nj] == '.' &&
!(*lookup)[ni][nj]) {
(*lookup)[ni][nj] = true;
if ((*matching)[ni][nj].first == -1 ||
dfs(seats, (*matching)[ni][nj], lookup, matching)) {
(*matching)[ni][nj] = e;
return true;
}
}
}
return false;
}
};
// Time: O(m * 2^n * 2^n) = O(m * 4^n)
// Space: O(2^n)
// dp solution
class Solution3 {
public:
int maxStudents(vector<vector<char>>& seats) {
const int state_size = 1 << seats[0].size();
unordered_map<int, int> dp;
dp[0] = 0;
for (const auto& row : seats) {
int invalid_mask = 0;
for (int i = 0; i < row.size(); ++i) {
if (row[i] == '#') {
invalid_mask |= 1 << i;
}
}
unordered_map<int, int> new_dp;
for (const auto& [mask1, v1] : dp) {
for (int mask2 = 0; mask2 < state_size; ++mask2) {
if ((mask2 & invalid_mask) ||
(mask2 & (mask1 << 1)) || (mask2 & (mask1 >> 1)) ||
(mask2 & (mask2 << 1)) || (mask2 & (mask2 >> 1))) {
continue;
}
new_dp[mask2] = max(new_dp.count(mask2) ? new_dp[mask2] : 0,
v1 + __builtin_popcount(mask2));
}
}
dp = move(new_dp);
}
return dp.empty() ? 0 : max_element(dp.cbegin(), dp.cend(),
[](const auto& a, const auto& b) {
return a.second < b.second;
})->second;
}
};
Beginner Explanation
What is Maximum Students Taking Exam?
Maximum Students Taking Exam (LeetCode #1349) is a Hard problem that primarily trains graph.
How to think about it
- Restate the goal in your own words before coding.
- Work a tiny example by hand so the invariant becomes obvious.
- Identify the pattern — this problem aligns with graph algorithms.
- Only then translate the idea into code.
Why this problem matters
Hard problems force you to combine patterns and prove complexity carefully — interview gold. Official solution notes mention: Hopcroft-Karp Bipartite Matching, Hungarian Bipartite Matching, Maximum Independent Set.
AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.
Interview Walkthrough
Interview approach for Maximum Students Taking Exam
Opening (30–60 seconds)
- Clarify inputs/outputs and edge cases (empty input, single element, duplicates, overflow).
- State a brute force so the interviewer knows you can solve it naively.
- Propose the optimal direction tied to graph algorithms.
Core solution narrative
- Define the state you track (pointers, DP cell, set membership, stack top, etc.).
- Explain the transition when you process the next element.
- Call out time (O(m * n * sqrt(m * n))) and space (O(m + n)) before coding.
- Code cleanly; narrate variable names.
What interviewers listen for
- Correctness on edge cases
- Complexity honesty
- Ability to discuss trade-offs (e.g., hash map space vs. sort + two pointers)
Follow-up questions they may ask
- Can you solve it with less memory?
- What if the input stream is infinite / doesn't fit in RAM?
- How would tests look for adversarial inputs?
Optimized Approach
Optimized solution notes
The reference solutions on AlgoForge target O(m * n * sqrt(m * n)) time and O(m + n) space.
Pattern focus: graph algorithms
Use the pattern as a checklist:
- graph algorithms — confirm the invariant holds after each step
Multiple methods appear in the source solutions — compare them and explain when each is preferable.
Implementation tips
- Prefer readable names over micro-optimizations in interviews.
- Extract helpers only when they clarify (e.g., expand-around-center, DFS visit).
- After AC-level logic, re-scan for off-by-one and null checks.
Complexity Analysis
Complexity
| Measure | Bound |
|---|---|
| Time | O(m * n * sqrt(m * n)) |
| Space | O(m + n) |
How to justify this in an interview
- Time: count loops, map/set operations, and recursive branching; state average vs worst case if relevant.
- Space: include hash maps, recursion stack, and output allocation when the problem asks for it.
If your implementation differs from the reference, re-derive big-O from your code — never memorize a complexity you cannot defend.
Common Mistakes
Common mistakes on Maximum Students Taking Exam
- Skipping edge cases — empty collections, single-element inputs, max constraints.
- Wrong invariant for graph algorithms — updating state too early or too late.
- Mutating input unexpectedly when the problem forbids it.
- Off-by-one in windows, ranges, or binary search bounds.
- Ignoring overflow / precision for integer arithmetic problems.
- Overengineering — jumping to an advanced structure when a simpler approach works.
Alternative Approaches
Alternatives
The source file includes more than one method. Compare:
- Primary optimized path — best complexity for typical interviews.
- Secondary approach — often brute force, sorting-based, or space-optimized variant.
Practice articulating when you would pick each (constraints, readability, follow-ups).
Edge Cases
Edge cases checklist
- Minimum input size
- Maximum input size / time limits
- Duplicates and already-sorted input
- Negative numbers / zeros (if applicable)
- Disconnected structures (graphs/trees)
- Single path vs branching recursion depth
Pattern Recognition
Spotting this pattern
Signal phrases that point to graph algorithms:
- Sorted input or ability to sort without changing the answer class
- Need for contiguous subarray / substring → consider sliding window
- Need for O(1) membership → hash set/map
- Optimal substructure + overlapping subproblems → DP
- Connectivity / components → graph DFS/BFS or Union-Find
Primary topics: graph.
Follow-up Interview Questions
Follow-ups
- How does the solution change if the input is a stream?
- Can you solve it in-place?
- What if duplicates must be handled differently?
- How would you parallelize the approach?
- Design tests that would break a buggy implementation.
Practice Recommendations
What to practice next
- Re-solve Maximum Students Taking Exam in a second language (cpp, python).
- Drill 3–5 more problems tagged graph.
- Teach the solution out loud in under 5 minutes.
- Add this problem to your revision calendar in 3 days and 14 days.
Visualization
Study checklist
- Read the official problem statement on LeetCode
- Solve on paper / whiteboard first
- Implement the graph algorithms approach
- Verify edge cases from the checklist
- State time and space complexity aloud
- Compare with the AlgoForge reference solution
- Schedule a revision session
Revision notes
Maximum Students Taking Exam (#1349) — Hard. Pattern: graph algorithms. Complexity: O(m * n * sqrt(m * n)) time / O(m + n) space. Re-derive the invariant before coding.
FAQs
What is the time complexity of Maximum Students Taking Exam?+
The reference solutions aim for O(m * n * sqrt(m * n)) time and O(m + n) space. Always re-derive complexity from the code you write in the interview.
What pattern does Maximum Students Taking Exam use?+
It primarily maps to graph algorithms, within the broader topic of graph.
Is Maximum Students Taking Exam good for interviews?+
Yes — as a Hard problem it is a solid practice target. Pair it with related problems in the same pattern family for spaced repetition.
Where can I read the official statement?+
Open the official LeetCode page for constraints and examples: https://leetcode.com/problems/maximum-students-taking-exam/