Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Remove Max Number of Edges to Keep Graph Fully Traversable

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1579" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Alice and Bob have an undirected graph of n nodes and three types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed by Bob only. Type 3: Can be traversed by both Alice and Bob. Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph. Example 1: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]] Output: 2 Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2. Example 2: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]] Output: 0 Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob. Example 3: Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]] Output: -1 Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable. Constraints: 1 <= n <= 105 1 <= edges.length <= min(105, 3 n (n - 1) / 2) edges[i].length == 3 1 <= typei <= 3 1 <= ui < vi <= n All tuples (typei, ui, vi) are distinct.

Explanation

Here's the solution to the problem, with a focus on efficiency:

  • Core Idea: Use the Union-Find (Disjoint Set Union) data structure to efficiently track connected components for Alice and Bob separately. Prioritize type 3 edges (common to both) to maximize the initial connectivity.

  • Connectivity Check: After processing edges, check if both Alice and Bob can traverse the entire graph (i.e., have only one connected component each). If not, return -1.

  • Edge Removal Count: The maximum number of removable edges is the difference between the total number of edges and the minimum number of edges required to connect the graph for both Alice and Bob.

  • Complexity:

    • Runtime: O(m * alpha(n)), where m is the number of edges and alpha(n) is the inverse Ackermann function (effectively constant time for practical input sizes).
    • Storage: O(n) for the Union-Find data structures.

Code

    class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n
        self.count = n  # Number of connected components

    def find(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.find(self.parent[i])  # Path compression
        return self.parent[i]

    def union(self, i, j):
        root_i = self.find(i)
        root_j = self.find(j)
        if root_i != root_j:
            if self.rank[root_i] < self.rank[root_j]:
                self.parent[root_i] = root_j
            elif self.rank[root_i] > self.rank[root_j]:
                self.parent[root_j] = root_i
            else:
                self.parent[root_j] = root_i
                self.rank[root_i] += 1
            self.count -= 1

class Solution:
    def maxNumEdgesToRemove(self, n: int, edges: list[list[int]]) -> int:
        alice_uf = UnionFind(n)
        bob_uf = UnionFind(n)
        removed_edges = 0

        # Process type 3 edges first
        for typei, u, v in edges:
            if typei == 3:
                if alice_uf.find(u - 1) != alice_uf.find(v - 1):
                    alice_uf.union(u - 1, v - 1)
                    bob_uf.union(u - 1, v - 1)
                else:
                    removed_edges += 1

        # Process type 1 edges (Alice only)
        for typei, u, v in edges:
            if typei == 1:
                if alice_uf.find(u - 1) != alice_uf.find(v - 1):
                    alice_uf.union(u - 1, v - 1)
                else:
                    removed_edges += 1

        # Process type 2 edges (Bob only)
        for typei, u, v in edges:
            if typei == 2:
                if bob_uf.find(u - 1) != bob_uf.find(v - 1):
                    bob_uf.union(u - 1, v - 1)
                else:
                    removed_edges += 1

        # Check if both Alice and Bob can fully traverse the graph
        if alice_uf.count != 1 or bob_uf.count != 1:
            return -1

        return removed_edges

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Remove Max Number of Edges to Keep Graph Fully Traversable