⭐ JS | Simple & Explained | Union Find
684. Redundant Connection \uD83D\uDE80\n\n### Solution Developed In:\n\n\n## The Question\nFor this article we will be covering Leetcode\'s \'684. Redundant Con
# 684. Redundant Connection \uD83D\uDE80\n***\n### Solution Developed In:\n![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)\n\n## The Question\nFor this article we will be covering Leetcode\'s \'[684. Redundant Connection](https://leetcode.com/problems/redundant-connection/)\' question. Knowing how to solve this problem with UnionFind will be vital to solving [1584. Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/)\' with [Kruskal\'s Algorithm](https://leetcode.com/problems/kruskal-algorithm/).\n\nQuestion:\n\n> In this problem, a tree is an **undirected graph** that is connected and has no cycles.\n> You are given a graph that started as a tree with n nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. The graph is represented as an array edges of length n where edges`[i] = [ai, bi]` indicates that there is an `edge` between nodes ai and bi in the graph.\n> Return an edge that can be removed so that the resulting graph is a tree of `n` nodes. If there are multiple answers, return the answer that occurs last in the input.\n\n![Example](https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg)\n\n>![Example](https://upload.wikimedia.org/wikipedia/commons/a/a3/UnionFindKruskalDemo.gif)\n\n```\nInput: edges = [[1,2],[1,3],[2,3]]\nOutput: [2,3]\n```\n\n## Explaining The Question\nThis Question is rated **Medium**. Which is for the most part accurate. This question is kinda of a trick question, if you\'re like me you\'ll probably think \'Greedy Depth First Search on all nodes until we find out last loop\'. Which works, but is not the best way to solve this problem.\n\nWhat\'s expected of you is to use [Union Find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) to solve this problem. Specifically, [Union Find by Rank](https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Union-find_by_rank) is expected.\n\nThis question is only **Medium** if you know how to use [Union Find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) with [Union Find by Rank](https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Union-find_by_rank).\n\nWe have been given a list of Nodes and Edges ([Node -> Edge]). Which forms a [Graph](https://en.wikipedia.org/wiki/Graph_(abstract)), we need to find the [Redundant Edge](https://en.wikipedia.org/wiki/Redundant_edge). Which is the last connection between two nodes that forms a [Cycle](https://en.wikipedia.org/wiki/Cycle_(graph_theory)).\n\n***\n\n##  Recommended Knowledge\n1. [Graph Theory](https://en.wikipedia.org/wiki/Graph_theory#:~:text=In%20mathematics%2C%20graph%20theory%20is,also%20called%20links%20or%20lines)\n2. [Union Find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure)\n3. [Union Find by Rank](https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Union-find_by_rank)\n4. [Path Compression](https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Path_compression)\n5. [Amortized Analysis](https://en.wikipedia.org/wiki/Amortized_analysis)\n\n## What do we know?\n1. We have a 2D Array of `\'1\'`s and `\'0\'`s.\n2. It\'s a *M x N* Matrix\n3. Neighbors are left, right, top, and bottom.\n4. We need to find the max area of an island. Meaning, the number of cells in the island.\n\n## How we\'re going to do it:\n\nWe\'re going to find this [Redundant Edge](https://en.wikipedia.org/wiki/Redundant_edge) by using a [Union Find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) data structure. We\'ll be creating a Tree from the provided Node & Edge array. The reasons this will work is because within a tree, there are no cycles. So when we\'re creating the tree, we\'ll be checking if the 2 given nodes have the same parent. What that mean\'s their was an attempt to create a connection in what was once a perfect tree. \n\nOnce we detect that attempted connection, we can identify the Node Edge that would\'ve created a redundant connection. \n\n1. We\'re going to firstly define our Ranks and Parents. A rank is the number of nodes that tree has. A parent is the node that is the parent of the current node. With this information, we know the size and structure of the tree. \n2. We\'re going to define our `Find()` function. When we\'re Unioning two nodes, we need to find the parents of the given node. We implement this function by asking the parents array, \'Who this nodes parent?\' and we keep asking this question until the parent of a node is itself (Meaning, it\'s the root). We also implement a [Path Compression](https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Path_compression) technique to speed up this process to achieve an Amortized O(1) time complexity.\n3. We\'re going to define our `Union()` function. The purpose of this function is to merge 2 trees together. Firstly, we need to `Find()` the root nodes of the 2 supplied nodes. We check if they\'re of the same parent, meaning it\'s a redundant connection and we need to stop execution. If they\'re not, we need to merge the 2 trees. We do this by setting the parent of the 2 nodes to the same parent. As well as updating their ranks\n4. Now we have all of our functions for a UnionFind structure, we will now attempt to Union all the supplied nodes. If at any point our Union connection returns false (Found a redundant connection), we can stop execution and return that edge.\n\n## Big O Notation:\n* Time Complexity:   *O(**V * E**)*  / *O(**n**)* | Where ***n*** is the number of nodes in the Graph. As we\'re going to visit every node in the matrix. Where ***V*** is the number of nodes in the graph and ***E*** is the number of edges in the graph. As in the worst case, the last node will attempt a redundant connection. \n\n* Space Complexity: *O(**h**)* | Where ***h*** is the largest number of nodes within our graph. As we\'re going to create a tree from the graph. Which will be the same as the number of nodes in the graph.\n\nWe did although implemented a [Path Compression](https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Path_compression) and [Union by Rank](https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Union-find_by_rank) technique to achieve a Amortized O(1) time complexity on our Union and Find functions. But as we will still need to iterate through the Nodes, we will still have a O(**n**) time complexity.\n## Leetcode Results:\n\nSee Submission Link: \n\n* Runtime: 78 ms, faster than ***85.83%*** of JavaScript online submissions for Max Area of Island\n* Memory Usage: 45.1 MB, less than ***67.24%*** of JavaScript online submissions for Max Area of Island.\n\n[![LeetCode](https://img.shields.io/badge/LeetCode-000000?style=for-the-badge&logo=LeetCode&logoColor=#d16c06)](https://leetcode.com/submissions/detail/716824590/)\n\n\n***\n\n# The Solution\n```\nclass UnionFind {\n    \n    /**\n\t * @summary We\'re going to generate a UnionFind data structure.\n\t * Union Find is a special data-structure that can be used to form\n\t * a disjoint set (A tree). For this solution, we\'re going to use\n\t * the Rank variant of Union Find. All this mean\'s is that we keep\n\t * track the number of nodes a given tree has. It allows us to merge\n\t * trees that will require the minimal amount of work (Increases\n\t * the Amortized Complexity).\n\t *\n\t * @param  {Array} edges [[node, edge_to_connect_to], [node, edge_to_connect_to]]\n\t */\n    constructor(edges) {\n\n        // Create a array of Ranks (Index -> Tree Size)\n        // Looks Like: [1,1,1,1]\n        // (Each node is a tree of size 1 by default)\n        this.ranks = new Array(edges.length).fill(1);\n\n        // Create a array of Parents (Index -> Index of Parent)\n        // If we keep following the parent, we\'ll eventually find\n        // the root of the tree.\n        // Looks Like: [0,1,2,3]\n        // (Each node\'s parent is itself by default, as it\'s the root of it\'s tree)\n        this.parents = Array.from(Array(edges.length).keys());\n    }\n\n    /**\n\t * @summary Find the root of a given node, we do this by asking the parents\n\t * list \'Who\'s the parent of this node\'s index?\', we repeat this until the parent\n\t * of the node is itself. Meaning, we have reached the root of the tree.\n\t * We have also utilized a concept called \'Path Compression\'. This mean\'s\n\t * instead of going up the tree one node at a time, we go up the tree 2 nodes\n\t * at a time. Tree height should be very small due to the \'rank\' concept.\n\t *\n\t * Time Complexity: Amortized O(1) (Best, tree height is small)\n\t   *              : O(log n) (Average)\n\t   *              : O(n) (Worst, linked list tree)\n\t *\n\t * Space Complexity: O(1) (Finding allocated no space)\n\t *\n\t * Technically, we rate an algorithm by it\'s worst case. Thus this is\n\t * O(n) in time. But it\'s such a rare case that we don\'t care, so it\'s better\n\t * to use the amortized case of O(1)\n\t *\n\t * @param  {Number} index (Index of node in [Parents, Ranks, Edges])\n\t * @return {Number}       (Index of parent, the root node of the tree)\n\t */\n    find(index) {\n        // Get parent of node\n        let parent = this.parents[index];\n\n        // Keep getting parents until we reach the root of the tree\n        while (parent != this.parents[parent]) {\n            // Path Compression\n            parent = this.parents[this.parents[parent]];\n        }\n        return parent;\n    }\n\n    /**\n\t * @summary Merge two trees by connecting the root of the  tree by rank.\n\t * What this mean\'s, is we\'re going to find the parents of both of the supplied\n\t * nodes, and then figure out which tree is larger. We then connect the root of\n\t * the smaller tree to the root of the larger tree.\n\t * Why? Because, during the Find() operation, we want to reduce the number of\n\t * steps required to get to the root of a given tree. By merging smaller into larger\n\t * we won\'t need as many steps to find the root of a given parent.\n\t *\n\t * This is called Union by Rank. Rank meaning, size of a given tree. When you combine\n\t * Path Compression and Union by Rank, you get a amortized O(1) time complexity.\n\t *\n\t * Time and Space Complexity is the same as Find() as we utilise that function.\n\t *\n\t * @param  {Number} n1 (Index of node 1)\n\t * @param  {Number} n2 (Index of node 2)\n\t * @return {Boolean}   (False if nodes are already in the same tree)\n\t */\n    union(n1, n2) {\n\n        // Find the parents of each node.\n        const n1_parent = this.find(n1);\n        const n2_parent = this.find(n2);\n\n        // Are the nodes already in the same tree?\n        // REDUNDANT CONNECTION!!!\n        if (n1_parent === n2_parent) return false;\n\n        // Union by rank, merge smallest into largest.\n        if (this.ranks[n1_parent] > this.ranks[n2_parent]) {\n            // Update parent and ranks\n            this.parents[n2_parent]  = n1_parent;\n            this.ranks  [n2_parent] += this.ranks[n1_parent];\n        } else {\n            // Merge n1 into n2\n            this.parents[n1_parent]  = n2_parent;\n            this.ranks  [n1_parent] += this.ranks[n2_parent];\n        }\n\n        // Successfully merged. Ranks and parents updated\n        return true;\n    }\n}\n\n/**\n * @param {number[][]} edges\n * @return {number[]}\n */\nvar findRedundantConnection = function (edges) {\n    // The basic premise of this solution is\n    // to use UnionFind to find the redundant edge.\n    // UnionFind will attempt to create a tree by merging nodes\n    // together. If at any point, two nodes are already connected,\n    // meaning, they\'re in the same tree, we have found the redundant connection.\n\n    // We\'re going to initialize a Union Find data structure\n    // so we can attempt to build our tree.\n    const Union_Find = new UnionFind(edges);\n\n    // Let\'s build our tree.\n    // Union each node and their edges together.\n    // If at any point, a node and edge are already in the same Tree.\n    // END loop, we found the redundant connection.\n    for (const [node, edge] of edges) {\n        if (!Union_Find.union(node, edge)) return [node, edge];\n    }\n};\n\n```
['Depth-First Search', 'Union Find', 'JavaScript']