Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 1319 · Union Find / DSU

Number of Operations to Make Network Connected

LeetCode 1319 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Count extra edges and components with DSU.

मध्यमDepth-First SearchBreadth-First SearchUnion-FindGraph Theory

मी Number of Operations to Make Network Connected (LeetCode 1319) असा सोडवला — Union Find / DSU पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Every cable that connects two already-connected computers is spare. To join k components you need k − 1 cables, so it's possible exactly when spare cables ≥ components − 1.

Approach

  1. 1

    Union each connection; already connected → extras++.

  2. 2

    Count components.

  3. 3

    required = components − 1; return it if extras suffice, else −1.

मी कसा सोडवला

DSUPythonO(E α(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 makeConnected(self, n: int, connections: List[List[int]]) -> int:
       ds = DisjointSet(n)
       extras=0
       for u,v in connections:
            if ds.find(u)==ds.find(v):
                extras+=1
            else:
                ds.union(u,v)
       components = 0
       for u in range(n):
        if ds.parent[u]==u:
            components+=1
       required = components-1
       if required<=extras:
            return required
       else:
            return -1
        
स्टेप-थ्रू लोड होत आहे…

Number of Operations to Make Network Connected — वारंवार विचारले जाणारे प्रश्न

Number of Operations to Make Network Connected मागील intuition काय आहे?

Every cable that connects two already-connected computers is spare. To join k components you need k − 1 cables, so it's possible exactly when spare cables ≥ components − 1.

Number of Operations to Make Network Connected (LeetCode 1319) कसा सोडवावा?

1. Union each connection; already connected → extras++. 2. Count components. 3. required = components − 1; return it if extras suffice, else −1.

Number of Operations to Make Network Connected ची time आणि space complexity किती आहे?

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

Number of Operations to Make Network Connected मध्ये सामान्य चुका कोणत्या?

Fewer than n − 1 cables total means −1 immediately.