{"id":35092,"date":"2024-11-01T09:35:25","date_gmt":"2024-11-01T09:35:25","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=35092"},"modified":"2024-11-01T11:45:01","modified_gmt":"2024-11-01T11:45:01","slug":"kotlin-coding-test-course-union-find","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/35092\/","title":{"rendered":"Kotlin Coding Test Course, Union Find"},"content":{"rendered":"<p><body><\/p>\n<p>Hello! In this article, we will explore the Union-Find algorithm using Kotlin. The Union-Find is a method for efficiently managing a set data structure, primarily used to find and combine connected components. This algorithm is an important concept frequently employed in problems related to graph theory.<\/p>\n<h2>Problem Description<\/h2>\n<p>Here is a problem that can be solved using Union-Find. We will understand the significance of Union-Find through the problem of <strong>counting the number of connected components<\/strong>.<\/p>\n<h3>Problem: Counting Connected Components<\/h3>\n<p>You have a graph with N nodes and M edges. Each node is numbered from 1 to N. Given M edges as follows, write a program to count the number of connected components.<\/p>\n<h4>Input Format<\/h4>\n<pre>\nN M\nu1 v1\nu2 v2\n...\nuM vM\n    <\/pre>\n<p>Where <code>N<\/code> is the number of nodes, <code>M<\/code> is the number of edges, and <code>u_i<\/code> and <code>v_i<\/code> represent the endpoints of the i-th edge.<\/p>\n<h4>Output Format<\/h4>\n<p>Print the number of connected components in a single line.<\/p>\n<h4>Example<\/h4>\n<pre>\nInput:\n5 3\n1 2\n2 3\n4 5\n\nOutput:\n2\n    <\/pre>\n<p>By examining the graph given in the example, nodes 1, 2, and 3 form one connected component, while nodes 4 and 5 form another, resulting in a total of 2 connected components.<\/p>\n<h2>Introduction to the Union-Find Algorithm<\/h2>\n<p>The Union-Find (Union-Find) or Disjoint Set Union data structure supports two main operations:<\/p>\n<ul>\n<li><strong>Find<\/strong>: Finds the representative element of the set to which a specific element belongs.<\/li>\n<li><strong>Union<\/strong>: Combines two sets into one.<\/li>\n<\/ul>\n<p>Union-Find is primarily used to manage the connectivity of disconnected graphs, and it employs path compression and union by rank techniques for efficiency. These techniques help in quickly performing the &#8216;Find&#8217; operation by maintaining a tree structure after merging.<\/p>\n<h2>Implementing in Kotlin<\/h2>\n<p>Now, let&#8217;s implement Union-Find in Kotlin. Below is the code to solve the above problem.<\/p>\n<pre class=\"code\">\nclass UnionFind(val size: Int) {\n    private val parent = IntArray(size + 1) { it } \/\/ Initialize each node's parent to itself\n    private val rank = IntArray(size + 1) { 1 } \/\/ Initialize the rank of each set\n\n    \/\/ Find operation: Path compression technique\n    fun find(node: Int): Int {\n        if (parent[node] != node) {\n            parent[node] = find(parent[node]) \/\/ Recursively find the parent while compressing the path\n        }\n        return parent[node]\n    }\n\n    \/\/ Union operation: Merging sets based on rank\n    fun union(node1: Int, node2: Int) {\n        val root1 = find(node1)\n        val root2 = find(node2)\n\n        if (root1 != root2) {\n            if (rank[root1] > rank[root2]) {\n                parent[root2] = root1\n            } else if (rank[root1] < rank[root2]) {\n                parent[root1] = root2\n            } else {\n                parent[root2] = root1\n                rank[root1]++\n            }\n        }\n    }\n\n    \/\/ Counting the number of connected components\n    fun countComponents(): Int {\n        val rootSet = mutableSetOf<Int>()\n        for (i in 1..size) {\n            rootSet.add(find(i)) \/\/ Find the root of each node and add to the set\n        }\n        return rootSet.size \/\/ The number of unique roots is the number of connected components\n    }\n}\n\nfun main() {\n    val reader = System.`in`.bufferedReader()\n    val (n, m) = reader.readLine().split(\" \").map { it.toInt() }\n    val unionFind = UnionFind(n)\n\n    for (i in 0 until m) {\n        val (u, v) = reader.readLine().split(\" \").map { it.toInt() }\n        unionFind.union(u, v) \/\/ Combine the two nodes based on edge information\n    }\n\n    println(unionFind.countComponents()) \/\/ Output the number of connected components\n}\n    <\/int><\/pre>\n<h2>Code Explanation<\/h2>\n<p>The code above implements the Union-Find data structure. To store each node&#8217;s parent, it uses the <code>parent<\/code> array, and to store the rank (height) of each set, it uses the <code>rank<\/code> array.<\/p>\n<p>1. The <strong>Find<\/strong> method recursively finds the root of the node through path compression. In this process, all nodes directly point to the root, speeding up future searches.<\/p>\n<p>2. The <strong>Union<\/strong> method finds the roots of two nodes and connects the lower rank set to the higher rank set. If their ranks are equal, it connects one set to the root of the other and increases the rank.<\/p>\n<p>3. The <strong>countComponents<\/strong> method returns the number of connected components by finding the root for all nodes and counting the unique roots.<\/p>\n<h2>Time Complexity Analysis<\/h2>\n<p>Each operation of Union-Find is very fast and can be performed in nearly constant time. The average time complexity of this algorithm is as follows:<\/p>\n<ul>\n<li>Find: O(\u03b1(N))<\/li>\n<li>Union: O(\u03b1(N))<\/li>\n<\/ul>\n<p><code>\u03b1(N)<\/code> is the inverse of the Ackermann function, which grows extremely slowly. Therefore, Union-Find operates efficiently even with large datasets.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we learned about the basic concepts and applications of the Union-Find algorithm, as well as how to solve problems involving connected graphs. Implementing it in Kotlin not only allowed us to understand the theory but also provided practical experience, which will be beneficial for preparing for coding tests.<\/p>\n<p>Since the Union-Find algorithm is an important algorithm that can be used in various fields, it is highly recommended that you familiarize yourself with it. We will also have upcoming courses on other algorithms and data structures, so please stay tuned!<\/p>\n<footer>\n<p>I hope this article was helpful, and if you have any questions, please leave a comment!<\/p>\n<\/footer>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello! In this article, we will explore the Union-Find algorithm using Kotlin. The Union-Find is a method for efficiently managing a set data structure, primarily used to find and combine connected components. This algorithm is an important concept frequently employed in problems related to graph theory. Problem Description Here is a problem that can be &hellip; <a href=\"https:\/\/atmokpo.com\/w\/35092\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Kotlin Coding Test Course, Union Find&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[106],"tags":[],"class_list":["post-35092","post","type-post","status-publish","format-standard","hentry","category----en"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Kotlin Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/35092\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Kotlin Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Hello! In this article, we will explore the Union-Find algorithm using Kotlin. The Union-Find is a method for efficiently managing a set data structure, primarily used to find and combine connected components. This algorithm is an important concept frequently employed in problems related to graph theory. Problem Description Here is a problem that can be &hellip; \ub354 \ubcf4\uae30 &quot;Kotlin Coding Test Course, Union Find&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/35092\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:35:25+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:45:01+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/35092\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/35092\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Kotlin Coding Test Course, Union Find\",\"datePublished\":\"2024-11-01T09:35:25+00:00\",\"dateModified\":\"2024-11-01T11:45:01+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/35092\/\"},\"wordCount\":556,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Kotlin coding test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/35092\/\",\"url\":\"https:\/\/atmokpo.com\/w\/35092\/\",\"name\":\"Kotlin Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:35:25+00:00\",\"dateModified\":\"2024-11-01T11:45:01+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/35092\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/35092\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/35092\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Kotlin Coding Test Course, Union Find\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Kotlin Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/35092\/","og_locale":"ko_KR","og_type":"article","og_title":"Kotlin Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Hello! In this article, we will explore the Union-Find algorithm using Kotlin. The Union-Find is a method for efficiently managing a set data structure, primarily used to find and combine connected components. This algorithm is an important concept frequently employed in problems related to graph theory. Problem Description Here is a problem that can be &hellip; \ub354 \ubcf4\uae30 \"Kotlin Coding Test Course, Union Find\"","og_url":"https:\/\/atmokpo.com\/w\/35092\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:35:25+00:00","article_modified_time":"2024-11-01T11:45:01+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/35092\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/35092\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Kotlin Coding Test Course, Union Find","datePublished":"2024-11-01T09:35:25+00:00","dateModified":"2024-11-01T11:45:01+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/35092\/"},"wordCount":556,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Kotlin coding test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/35092\/","url":"https:\/\/atmokpo.com\/w\/35092\/","name":"Kotlin Coding Test Course, Union Find - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:35:25+00:00","dateModified":"2024-11-01T11:45:01+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/35092\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/35092\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/35092\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Kotlin Coding Test Course, Union Find"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/35092","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=35092"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/35092\/revisions"}],"predecessor-version":[{"id":35093,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/35092\/revisions\/35093"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=35092"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=35092"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=35092"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}