Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 684 · Union Find / DSU

Redundant Connection

LeetCode 684 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

First edge connecting an already-connected pair.

நடுத்தரம்Depth-First SearchBreadth-First SearchUnion-FindGraph Theory
LeetCode இல் திற ↗

நான் Redundant Connection (LeetCode 684) ஐ இப்படித் தீர்த்தேன் — Union Find / DSU பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Add edges one at a time with union-find. The first edge whose two ends are already in the same component closes a cycle — that's the redundant one.

Approach

  1. 1

    DSU over n nodes.

  2. 2

    For each edge, if find(u) == find(v), return it.

  3. 3

    Otherwise union.

நான் எப்படித் தீர்த்தேன்

DSUPythonO(n α(n)) time
class DisjointSet:
    def __init__(self,n):
        self.rank = [0]*(n+1)
        self.parent = [i for i in range(n+1)]
    def find(self,u):
        if self.parent[u]==u:
            return u
        self.parent[u]=self.find(self.parent[u])
        return self.parent[u]
    def union(self,u,v):
        pu,pv = self.find(u),self.find(v)
        if pu==pv:
            return 
        if self.rank[pu]<self.rank[pv]:
            self.parent[pu]=pv
        elif self.rank[pv]<self.rank[pu]:
            self.parent[pv]=pu
        elif self.rank[pv]==self.rank[pu]:
            self.parent[pv]=pu
            self.rank[pu]+=1

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        n = len(edges)
        ds = DisjointSet(n)
        for u,v in edges:
            if ds.find(u)==ds.find(v):
                return [u,v]
            else:
                ds.union(u,v)
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Redundant Connection — அடிக்கடி கேட்கப்படும் கேள்விகள்

Redundant Connection பின்னாலுள்ள intuition என்ன?

Add edges one at a time with union-find. The first edge whose two ends are already in the same component closes a cycle — that's the redundant one.

Redundant Connection (LeetCode 684) ஐ எப்படித் தீர்ப்பது?

1. DSU over n nodes. 2. For each edge, if find(u) == find(v), return it. 3. Otherwise union.

Redundant Connection இன் time மற்றும் space complexity என்ன?

Time: O(n α(n)). Space: O(n). (Accepted approach: DSU.)

Redundant Connection இல் பொதுவான தவறுகள் என்ன?

Returning the first such edge matches 'the last one in input order' since only one edge closes the cycle.