โš”๏ธ
DSA Important Questions
  • ๐Ÿ˜‡README
  • ๐Ÿ”ซQuestion List
  • ๐ŸงชFormula List
  • ๐Ÿ—’๏ธ01 Array
    • โœ…Rotate Matrix
    • โœ…Max Sum Contiguous Subarray
    • Find Duplicate in Array
    • โœ…Merge Intervals
    • โœ…Spiral Order Matrix I
    • Repeat and Missing Number Array
    • โœ…Merge Overlapping Intervals
    • โœ…Set Matrix Zeros
    • โœ…Spiral Order Matrix II
    • Largest Number
    • First Missing Integer
    • โœ…Pascal Triangle
    • โญMax Distance
    • โœ…Wavy Array
    • Next Permutation
    • โœ…Min Steps in Infinite Grid
    • Flip
    • โญFind Permutation
    • โญMaximum Absolute Difference
    • โญMaximum Unsorted Subarray
    • Reorder Data in Log File
    • โœ…Make equal elements Array
  • โž•02 Math
    • โœ…Excel Column Number
    • โญExcel Column Title
    • โญGrid Unique Paths
    • โญPower Of Two Integers
    • โœ…Next Similar Number
    • โญk-th Permutation
  • ๐Ÿ”03 Binary Search
    • โญMedian of Array
    • โญSquare Root of Integer
    • โญRotated Sorted Array Search
    • โญMatrix Median
    • Capacity To Ship Packages Within B Days
  • ๐Ÿงต04 String
    • Implement StrStr
    • โญInteger to Roman
    • โญRoman to Integer
    • Length of Last Word
    • โญatoi
    • โญValid IP Addresses
    • โญCompare Version Numbers
    • โญLongest Palindromic Substring
    • Count And Say
    • Reverse the String
    • Power of 2
    • ๐ŸšงKMP: Minimum Characters Required to Make a String Palindromic
    • โญConvert to Palindrome
    • Bulls and Cows
  • 1๏ธโƒฃ05 Bit Manipulation
    • Reverse Bits
    • Single Number
    • โญDivide Integers
    • โญSingle Number II
    • โญCount Total Set Bits
    • โญPalindromic Binary Representation
  • โœŒ๏ธ06 Two Pointers
    • Merge Two Sorted Lists II
    • โญ3 Sum
    • Remove Duplicates from sorted Array
    • โญContainer With Most Water
    • Remove Element from Array
    • โญMax Continuous Series of 1s
    • Pair With Given Difference
    • โญMaximum Ones After Modification
  • ๐Ÿ”—07 Linked List
    • Swap List Nodes in Pairs
    • Rotate List
    • โญReorder List
    • Merge Two Sorted Lists
    • Remove Duplicates from Sorted List
    • Add Two Numbers as Lists
    • Remove Nth Node from List End
    • โญList Cycle
    • Intersection of Linked Lists
    • โญReverse Linked List II
    • Palindrome List
    • โญK reverse linked list
    • โญReverse Alternate K Nodes
    • โญKth Node From Middle
    • โญSort Binary Linked List
    • โญEven Reverse
  • ๐Ÿ“š08 Stacks and Queues
    • โญRain Water Trapping
    • Generate all Parentheses
    • โญLargest Rectangle in Histogram
    • โญMin Stack
    • Redundant Braces
    • Nearest Smaller Element
    • โญFirst non-repeating character in a stream of characters
    • โœ…Balanced Parantheses!
  • ๐Ÿ”™09 Backtracking
    • โญKth Permutation Sequence
    • โญCombination Sum
    • Combination Sum II
    • โญNQueens
    • Combinations
    • โญSubsets II
    • Subset
    • Palindrome Partitioning
  • ๐Ÿ’ฑ10 Hashing
    • โญLongest Consecutive Sequence
    • โญ4 Sum
    • โญAnagrams
    • โญPoints on the Straight Line
    • 2 Sum
    • โญValid Sudoku
    • Copy List
    • Longest Substring Without Repeat
  • ๐Ÿ—ป11 Heaps & Maps
    • Merge K Sorted Lists
    • โญLRU Cache
    • โญInversions
    • Distinct Numbers in Window
  • ๐ŸŒณ12 Tree Data Structure
    • โœ…Inorder Traversal
    • โญRecover Binary Search Tree
    • โญInorder Traversal of Cartesian Tree
    • โญLeast Common Ancestor
    • โญConstruct Binary Tree From Inorder And Preorder
    • Flatten Binary Tree to Linked List
    • Valid Binary Search Tree
    • โœ…Preorder Traversal
    • โญBinary Tree From Inorder And Postorder
    • Balanced Binary Tree
    • โœ…Sorted Array To Balanced BST
    • Symmetric Binary Tree
    • โœ…Postorder Traversal
    • โญPopulate Next Right Pointers Tree
    • Identical Binary Trees
    • BST Iterator
    • ZigZag Level Order Traversal BT
    • Path Sum
    • Next Pointer Binary Tree
    • Min Depth of Binary Tree
    • Root to Leaf Paths With Sum
    • โญKth Smallest Element in Tree
    • โญ2-Sum Binary Tree
    • Vertical Order traversal of Binary Tree
    • โญDiagonal Traversal
    • Cousins in Binary Tree
    • Path to Given Node
    • Remove Half Nodes
    • Merge two Binary Tree
    • โญBurn a Tree
    • Nodes at Distance K
    • Vertical Sum of a Binary Tree
    • Covered / Uncovered Nodes
  • 13 Dynamic Programming
    • Ugly Number II
    • Coin Change
    • 0 - 1 Knapsack Problem
    • Permutation Coefficient
  • 14 Greedy Algorithm
    • โญGas Station
    • โญMajority Element
    • โญDistribute Candy
    • โญHighest Product
    • Assign Mice to Holes
    • โญMeeting rooms
  • ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ15 Graph
    • Clone Graph
    • Word Search Board
    • โญStepping Numbers
    • Black Shapes
    • Knight On Chess Board
    • โŒSmallest Multiple With 0 and 1
    • โญCommutable Islands
    • Possibility of finishing all courses given pre-requisites
    • โŒValid Path
    • Cycle in Directed Graph
    • โŒCycle in Undirected Graph
Powered by GitBook
On this page
  • Using Prim's Brute Force
  • Using Optimized Prim's
  • Using Kruskal's Algorithm
  1. 15 Graph

Commutable Islands

PreviousSmallest Multiple With 0 and 1NextPossibility of finishing all courses given pre-requisites

Last updated 2 years ago

Using Prim's Brute Force

#include <bits/stdc++.h>
int Solution::solve(int A, vector<vector<int> > &B) {
    // adj[u] = {(v1, w2) , (v2, w2)...}
    vector<pair<int, int>> adj[A + 1];
    for(vector<int> edgeAndWeight : B) {
        int u = edgeAndWeight[0];
        int v = edgeAndWeight[1];
        int w = edgeAndWeight[2];
        
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    
    vector<int> weight(A + 1, INT_MAX);
    weight[0] = weight[1] = 0;
    vector<bool> mst(A + 1);
    for(int bridgeCount = 1; bridgeCount <= A - 1; bridgeCount++
        int minWeight = INT_MAX;
        int node = -1;
        for(int i = 1; i <= A; i++)
            if(!mst[i] && weight[i] < minWeight) {
                minWeight = weight[i];
                node = i;
            }        
            
        mst[node] = true;
        
        for(pair<int, int> neighbourWithWeight: adj[node]) {
            int neighbour = neighbourWithWeight.first;
            int costToNeighbour = neighbourWithWeight.second;
            
            if(mst[neighbour] == false && costToNeighbour < weight[neighbour]) 
                weight[neighbour] = costToNeighbour;
        }
    }
    
    return accumulate(weight.begin(), weight.end(), 0);
}

Time Complexity: O(n2)O(n^2)O(n2)โ€‹ for Aโˆ’1A - 1Aโˆ’1 edges and for finding minimum

Space Complexity: O(2V)+O(V)+O(V)O(2V) + O(V) +O(V)O(2V)+O(V)+O(V) for adjacency list, weights, and MST.

Using Optimized Prim's

#include <bits/stdc++.h>
int Solution::solve(int A, vector<vector<int> > &B) {
    vector<pair<int, int>> adj[A + 1];
    vector<bool> mst(A + 1);
    
    for(vector<int> edge: B) {
        int u = edge[0];
        int v = edge[1];
        int w = edge[2];
        
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    
    vector<int> weight(A + 1, INT_MAX);
    weight[0] = weight[1] = 0;
    
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, 1});
    
    for(int edgeCount = 1; edgeCount <= A - 1; edgeCount++) {
        int node = pq.top().second;
        pq.pop();
        
        mst[node] = true;
        
        for(pair<int, int> neighbourWithWeight: adj[node]) {
            int neighbour = neighbourWithWeight.first;
            int neighbourWeight = neighbourWithWeight.second;
            
            if(mst[neighbour] == false && neighbourWeight < weight[neighbour]) {
                weight[neighbour] = neighbourWeight;
                pq.push({weight[neighbour], neighbour});
            }
        }    
    }
    return accumulate(weight.begin(), weight.end(), 0);     
}

Using Kruskal's Algorithm

bool cmp(const vector<int> &edge1, const vector<int> &edge2) {
    return edge1[2] < edge2[2];
}

int findParent(int u, vector<int> &parent) {
    if(u == parent[u])
        return u;
        
    return parent[u] = findParent(parent[u], parent);
}

void performUnion(int u, int v, vector<int> &parent, vector<int> &rank) {
    u = findParent(u, parent);
    v = findParent(v, parent);
    
    if(rank[u] < rank[v]) 
        parent[u] = v;
    else if(rank[v] < rank[u])
        parent[v] = u;
    else {
        parent[v] = u;
        rank[u]++;
    }
}

int Solution::solve(int A, vector<vector<int> > &B) {
    sort(B.begin(), B.end(), cmp);
    
    // Initialize disjoint data structure
    vector<int> parent(A + 1);
    for(int i = 1; i < A; i++)
        parent[i] = i;
        
    vector<int> rank(A + 1);
    
    // take each edge in the order of smallest to largest weights
    int cost = 0;
    for(const vector<int> &closestNode: B) {
        // if disjoint then merge
        if(findParent(closestNode[0], parent) != findParent(closestNode[1], parent)) {
            cost += closestNode[2];
            performUnion(closestNode[0], closestNode[1], parent, rank);
        }
    }
    
    return cost;
}
๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ
โญ
Commutable Islands - InterviewBitInterviewBit
Logo