💻
LeetCode -> NeetCode
  • Leetcode
  • 1. Two Sum
    • CODE
  • 100. Same Tree
    • CODE
  • 102. Binary Tree Level Order Traversal
    • CODE
  • 103. Binary Tree Zigzag Level Order Traversal
    • CODE
  • 104. Maximum Depth of Binary Tree
    • CODE
  • 1041. Robot Bounded In Circle
    • CODE
  • 1046. Last Stone Weight
    • CODE
  • 105. Construct Binary Tree from Preorder and Inorder Traversal
    • CODE
  • 11. Container With Most Water
    • CODE
  • 110. Balanced Binary Tree
    • CODE
  • 111. Minimum Depth of Binary Tree
    • CODE
  • 112. Path Sum
    • CODE
  • 1143. Longest Common Subsequence
    • CODE
  • 116. Populating Next Right Pointers in Each Node
    • CODE
  • 121. Best Time to Buy and Sell Stock
    • CODE
  • 124. Binary Tree Maximum Path Sum
    • CODE
  • 125. Valid Palindrome
    • CODE
  • 128. Longest Consecutive Sequence
    • CODE
  • 130. Surrounded Regions
    • CODE
  • 131-palindrome-partitioning
    • CODE
  • 133. Clone Graph
    • CODE
  • 134. Gas Station
    • CODE
  • 136. Single Number
    • CODE
  • 138. Copy List with Random Pointer
    • CODE
  • 139. Word Break
    • CODE
  • 141. Linked List Cycle
    • CODE
  • 143. Reorder List
    • CODE
  • 1448. Count Good Nodes in Binary Tree
    • CODE
  • 146. LRU Cache
    • CODE
  • 1481. Least Number of Unique Integers after K Removals
    • CODE
  • 15. 3Sum
    • CODE
  • 150. Evaluate Reverse Polish Notation
    • CODE
  • 152. Maximum Product Subarray
    • CODE
  • 153. Find Minimum in Rotated Sorted Array
    • CODE
  • 1539. Kth Missing Positive Number
    • CODE
  • 155. Min Stack
    • CODE
  • 1584. Min Cost to Connect All Points
    • CODE
  • 162. Find Peak Element
    • CODE
  • 167. Two Sum II - Input Array Is Sorted
    • CODE
  • 17. Letter Combinations of a Phone Number
    • CODE
  • 1834. Single-Threaded CPU
    • CODE
  • 1899-merge-triplets-to-form-target-triplet
    • CODE
  • 19. Remove Nth Node From End of List
    • CODE
  • 190. Reverse Bits
    • CODE
  • 191. Number of 1 Bits
    • CODE
  • 198. House Robber
    • CODE
  • 199. Binary Tree Right Side View
    • CODE
  • 2. Add Two Numbers
    • CODE
  • 20. Valid Parentheses
    • CODE
  • 200. Number of Islands
    • CODE
  • 2013. Detect Squares
    • CODE
  • 202. Happy Number
    • CODE
  • 2055. Plates Between Candles
    • CODE
  • 206. Reverse Linked List
    • CODE
  • 207. Course Schedule
    • CODE
  • 208. Implement Trie (Prefix Tree)
    • CODE
  • 21. Merge Two Sorted Lists
    • CODE
  • 211. Design Add and Search Words Data Structure
    • CODE
  • 212. Word Search II
    • CODE
  • 213. House Robber II
    • CODE
  • 215. Kth Largest Element in an Array
    • CODE
  • 217. Contains Duplicate
    • CODE
  • 226. Invert Binary Tree
    • CODE
  • 23. Merge k Sorted Lists
    • CODE
  • 230. Kth Smallest Element in a BST
    • CODE
  • 235. Lowest Common Ancestor of a Binary Search Tree
    • CODE
  • 238. Product of Array Except Self
    • CODE
  • 239. Sliding Window Maximum
    • CODE
  • 242. Valid Anagram
    • CODE
  • 252-meeting-rooms
    • CODE
  • 253-meeting-rooms-ii
    • CODE
  • 268. Missing Number
    • CODE
  • 287. Find the Duplicate Number
    • CODE
  • 295. Find Median from Data Stream
    • CODE
  • 297. Serialize and Deserialize Binary Tree
    • CODE
  • 3. Longest Substring Without Repeating Characters
    • CODE
  • 300. Longest Increasing Subsequence
    • CODE
  • 322. Coin Change
    • CODE
  • 33. Search in Rotated Sorted Array
    • CODE
  • 338. Counting Bits
    • CODE
  • 347. Top K Frequent Elements
    • CODE
  • 35. Search Insert Position
    • CODE
  • 355. Design Twitter
    • CODE
  • 36. Valid Sudoku
    • CODE
  • 371. Sum of Two Integers
    • CODE
  • 378. Kth Smallest Element in a Sorted Matrix
    • CODE
  • 39. Combination Sum
    • CODE
  • 4. Median of Two Sorted Arrays
    • CODE
  • 40. Combination Sum II
    • CODE
  • 417-pacific-atlantic-water-flow
    • CODE
  • 42-trapping-rain-water
    • CODE
  • 424. Longest Repeating Character Replacement
    • CODE
  • 43. Multiply Strings
    • CODE
  • 435. Non-overlapping Intervals
    • CODE
  • 436. Find Right Interval
    • CODE
  • 442. Find All Duplicates in an Array
    • CODE
  • 448. Find All Numbers Disappeared in an Array
    • CODE
  • 45. Jump Game II
    • CODE
  • 46. Permutations
    • CODE
  • 47. Permutations II
    • CODE
  • 48. Rotate Image
    • CODE
  • 49. Group Anagrams
    • CODE
  • 5. Longest Palindromic Substring
    • CODE
  • 50. Pow(x, n)
    • CODE
  • 51. N-Queens
    • CODE
  • 53. Maximum Subarray
    • CODE
  • 54. Spiral Matrix
    • CODE
  • 543. Diameter of Binary Tree
    • CODE
  • 547. Number of Provinces
    • CODE
  • 55. Jump Game
    • CODE
  • 554. Brick Wall
    • CODE
  • 56. Merge Intervals
    • CODE
  • 567. Permutation in String
    • CODE
  • 57. Insert Interval
    • CODE
  • 572. Subtree of Another Tree
    • CODE
  • 581. Shortest Unsorted Continuous Subarray
    • CODE
  • 61. Rotate List
    • CODE
  • 62. Unique Paths
    • CODE
  • 621. Task Scheduler
    • CODE
  • 647. Palindromic Substrings
    • CODE
  • 659 · Encode and Decode Strings
    • CODE
  • 66. Plus One
    • CODE
  • 695. Max Area of Island
    • CODE
  • 7. Reverse Integer
    • CODE
  • 70. Climbing Stairs
    • CODE
  • 703. Kth Largest Element in a Stream
    • CODE
  • 704. Binary Search
    • CODE
  • 73-set-matrix-zeroes
    • CODE
  • 739. Daily Temperatures
    • CODE
  • 74. Search a 2D Matrix
    • CODE
  • 746. Min Cost Climbing Stairs
    • CODE
  • 75. Sort Colors
    • CODE
  • 76-minimum-window-substring
    • CODE
  • 763. Partition Labels
    • CODE
  • 78. Subsets
    • CODE
  • 784. Letter Case Permutation
    • CODE
  • 79. Word Search
    • CODE
  • 796. Rotate String
    • CODE
  • 828. Count Unique Characters of All Substrings of a Given String
    • CODE
  • 832. Flipping an Image
    • CODE
  • 84. Largest Rectangle in Histogram
    • CODE
  • 846. Hand of Straights
    • CODE
  • 853. Car Fleet
  • 875. Koko Eating Bananas
    • CODE
  • 90. Subsets II
    • CODE
  • 904. Fruit Into Baskets
    • CODE
  • 91. Decode Ways
    • CODE
  • 973. K Closest Points to Origin
    • CODE
  • 977. Squares of a Sorted Array
    • CODE
  • 98. Validate Binary Search Tree
    • CODE
  • 981-time-based-key-value-store
    • CODE
  • 993. Cousins in Binary Tree
    • CODE
  • 994. Rotting Oranges
    • CODE
  • scripts
    • CODE
Powered by GitBook
On this page
Edit on GitHub
  1. 547. Number of Provinces

CODE

class Solution:
    def findCircleNum(self, isConnected: List[List[int]]) -> int:
        num_province = len(isConnected)
        # Array that stores the parent of a given node, initially
        # every node's parent is set itself
        ancestor = [i for i in range(num_province)]
        # Rank for each node
        rank = [1 for _ in range(num_province)]
        
        def find_ancestor(node):
            # While we dont reach to top most ancestor
            while node != ancestor[node]:
                # Path compression, for a give node, its grandparent is
                # is also a parent (ancestor) hence reduce the hop from 
                # child -> parent -> grandparent
                ancestor[node] = ancestor[ancestor[node]]
                # For the parent find its parent in the next iteration
                node = ancestor[node]
            # Should be the top most ancestor
            return node
                
        def union(node1, node2):
            node1_ancestor, node2_ancestor = find_ancestor(node1), find_ancestor(node2)
            # Both nodes have common ancestor, no need to union them
            if node1_ancestor == node2_ancestor:
                return 0
            
            # If node1 ancestor is elder (rank), ask node2 to merge into it
            # also, with the merge node1 ancestor is more elder now
            if rank[node1_ancestor] > rank[node2_ancestor]:
                ancestor[node2_ancestor] = node1_ancestor
                rank[node1_ancestor] += rank[node2_ancestor]
            else:
                ancestor[node1_ancestor] = node2_ancestor
                rank[node2_ancestor] += rank[node1_ancestor]
            return 1
                
        for node1 in range(len(isConnected)):
            for node2 in range(len(isConnected[0])):
                if isConnected[node1][node2] == 1:
                    num_province -= union(node1, node2)
        return num_province
        
Previous547. Number of ProvincesNext55. Jump Game

Last updated 2 years ago