#1820MediumPremium on LC~43 min

Maximum Number of Accepted Invitations

Time O(m * n * sqrt(m + n)) · Space O(m + n) · Official statement on LeetCode

cpppython

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 matcing
    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 maximumInvitations(vector<vector<int>>& grid) {
        BipGraph graph(size(grid), size(grid[0]));
        for (int i = 0; i < size(grid); ++i) {
            for (int j = 0; j < size(grid[0]); ++j) {
                if (!grid[i][j]) {
                    continue;
                }
                graph.addEdge(i + 1, j + 1);
            }
        }
        return graph.hopcroftKarp();
    }
};

// Time:  O(|V| * |E|) = O(min(m, n) * (m * n))
// Space: O(|V|) = O(min(m, n))
// Hungarian bipartite matching with less space
class Solution2 {
public:
    int maximumInvitations(vector<vector<int>>& grid) {
        return hungarian(grid);
    }

private:
    int hungarian(const vector<vector<int>>& grid) {
        unordered_map<int, int> match;
        for (int i = 0; i < min(size(grid), size(grid[0])); ++i) {
            unordered_set<int> lookup;  // visited u
            augment(grid, i, &lookup, &match);
        }
        return size(match);
    }

    bool augment(const vector<vector<int>>& grid, int u,
                 unordered_set<int> *lookup,
                 unordered_map<int, int> *match) {
        for (int v = 0; v < max(size(grid), size(grid[0])); ++v) {
            if (!get_grid(grid, u, v) || lookup->count(v)) {
                continue;
            }
            lookup->emplace(v);
            if (!match->count(v) || augment(grid, (*match)[v], lookup, match)) {
                (*match)[v] = u;
                return true;
            }
        }
        return false;
    }

    int get_grid(const vector<vector<int>>& grid, int u, int v) {
        return (size(grid) < size(grid[0])) ? grid[u][v] : grid[v][u];
    }
};

// Time:  O(|V| * |E|) = O(min(m, n) * (m * n))
// Space: O(|E|) = O(m * n)
// Hungarian bipartite matching
class Solution3 {
public:
    int maximumInvitations(vector<vector<int>>& grid) {
        unordered_map<int, vector<int>> adj;
        for (int i = 0; i < size(grid); ++i) {
            for (int j = 0; j < size(grid[0]); ++j) {
                if (!grid[i][j]) {
                    continue;
                }
                if (size(grid) < size(grid[0])) {
                    adj[i].emplace_back(j);
                } else {
                    adj[j].emplace_back(i);
                }
            }
        }
        return hungarian(adj);
    }

private:
    int hungarian(const unordered_map<int, vector<int>>& adj) {
        unordered_map<int, int> match;
        for (const auto& [i, _] : adj) {
            unordered_set<int> lookup;  // visited v
            augment(adj, i, &lookup, &match);
        }
        return size(match);
    }

    bool augment(const unordered_map<int, vector<int>>& adj, int u,
                 unordered_set<int> *lookup,
                 unordered_map<int, int> *match) {
        for (const auto& v : adj.at(u)) {
            if (lookup->count(v)) {
                continue;
            }
            lookup->emplace(v);
            if (!match->count(v) || augment(adj, (*match)[v], lookup, match)) {
                (*match)[v] = u;
                return true;
            }
        }
        return false;
    }
};

Beginner Explanation

What is Maximum Number of Accepted Invitations?

Maximum Number of Accepted Invitations (LeetCode #1820) is a Medium problem that primarily trains graph.

How to think about it

  1. Restate the goal in your own words before coding.
  2. Work a tiny example by hand so the invariant becomes obvious.
  3. Identify the pattern — this problem aligns with graph algorithms.
  4. Only then translate the idea into code.

Why this problem matters

It sits in the sweet spot of interview difficulty: multiple valid approaches, clear trade-offs. Official solution notes mention: Hopcroft-Karp Bipartite Matching, Hungarian Bipartite Matching.

AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.

Interview Walkthrough

Interview approach for Maximum Number of Accepted Invitations

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

  1. Define the state you track (pointers, DP cell, set membership, stack top, etc.).
  2. Explain the transition when you process the next element.
  3. Call out time (O(m * n * sqrt(m + n))) and space (O(m + n)) before coding.
  4. 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 Number of Accepted Invitations

  1. Skipping edge cases — empty collections, single-element inputs, max constraints.
  2. Wrong invariant for graph algorithms — updating state too early or too late.
  3. Mutating input unexpectedly when the problem forbids it.
  4. Off-by-one in windows, ranges, or binary search bounds.
  5. Ignoring overflow / precision for integer arithmetic problems.
  6. Overengineering — jumping to an advanced structure when a simpler approach works.

Alternative Approaches

Alternatives

The source file includes more than one method. Compare:

  1. Primary optimized path — best complexity for typical interviews.
  2. 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

  1. How does the solution change if the input is a stream?
  2. Can you solve it in-place?
  3. What if duplicates must be handled differently?
  4. How would you parallelize the approach?
  5. Design tests that would break a buggy implementation.

Practice Recommendations

What to practice next

  1. Re-solve Maximum Number of Accepted Invitations in a second language (cpp, python).
  2. Drill 3–5 more problems tagged graph.
  3. Teach the solution out loud in under 5 minutes.
  4. Add this problem to your revision calendar in 3 days and 14 days.

Visualization

Conceptual diagram for Maximum Number of Accepted Invitations: show input structure (graph), highlight the moving parts of the graph algorithms approach, and annotate each step with the maintained invariant and complexity.

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 Number of Accepted Invitations (#1820) — Medium. 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 Number of Accepted Invitations?+

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 Number of Accepted Invitations use?+

It primarily maps to graph algorithms, within the broader topic of graph.

Is Maximum Number of Accepted Invitations good for interviews?+

Yes — as a Medium 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-number-of-accepted-invitations/