{"id":34856,"date":"2024-11-01T09:32:46","date_gmt":"2024-11-01T09:32:46","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34856"},"modified":"2024-11-01T11:26:14","modified_gmt":"2024-11-01T11:26:14","slug":"swift-coding-test-course-lowest-common-ancestor","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34856\/","title":{"rendered":"Swift Coding Test Course, Lowest Common Ancestor"},"content":{"rendered":"<p><body><\/p>\n<p>This lecture will cover the Lowest Common Ancestor (LCA) problem. This problem involves finding the lowest common ancestor of two given nodes, a concept that is very useful in tree structures. It is particularly helpful in enhancing understanding of data structures and algorithms.<\/p>\n<h2>Problem Description<\/h2>\n<p>Write a function to find the lowest common ancestor of two nodes in a given binary tree. The binary tree is represented in the following format:<\/p>\n<pre>\n    class TreeNode {\n        var value: Int\n        var left: TreeNode?\n        var right: TreeNode?\n\n        init(value: Int) {\n            self.value = value\n            self.left = nil\n            self.right = nil\n        }\n    }\n    <\/pre>\n<h3>Input<\/h3>\n<ul>\n<li>The root node of the tree (root)<\/li>\n<li>The first node (first)<\/li>\n<li>The second node (second)<\/li>\n<\/ul>\n<h3>Output<\/h3>\n<p>Returns the lowest common ancestor of the given two nodes.<\/p>\n<h4>Example<\/h4>\n<pre>\n    Input:\n        root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]\n        first = 5\n        second = 1\n\n    Output: 3\n\n    Input:\n        root = [1, 2, 3]\n        first = 2\n        second = 3\n\n    Output: 1\n    <\/pre>\n<h2>Problem Approach<\/h2>\n<p>To solve this problem, the following approach can be taken:<\/p>\n<ol>\n<li>Start the search from the root of the tree.<\/li>\n<li>If the current node is one of the <code>first<\/code> or <code>second<\/code> nodes, return that node.<\/li>\n<li>Recursively search in the left and right children to find the <code>first<\/code> and <code>second<\/code> nodes.<\/li>\n<li>If both results from the left and right children are not nil, the current node is the lowest common ancestor.<\/li>\n<li>If only one side finds either <code>first<\/code> or <code>second<\/code>, return that child node.<\/li>\n<li>If nothing is found, return <code>nil<\/code>.<\/li>\n<\/ol>\n<h2>Swift Code Implementation<\/h2>\n<p>Based on this approach, let\u2019s implement the Swift code:<\/p>\n<pre>\n    class TreeNode {\n        var value: Int\n        var left: TreeNode?\n        var right: TreeNode?\n\n        init(value: Int) {\n            self.value = value\n            self.left = nil\n            self.right = nil\n        }\n    }\n\n    func lowestCommonAncestor(root: TreeNode?, first: Int, second: Int) -> TreeNode? {\n        \/\/ Base case: if the root is nil\n        guard let root = root else {\n            return nil\n        }\n\n        \/\/ If the current node is first or second node\n        if root.value == first || root.value == second {\n            return root\n        }\n\n        \/\/ Recursive calls for left and right children\n        let left = lowestCommonAncestor(root: root.left, first: first, second: second)\n        let right = lowestCommonAncestor(root: root.right, first: first, second: second)\n\n        \/\/ If both sides found the nodes\n        if left != nil && right != nil {\n            return root\n        }\n\n        \/\/ Return the found node from one side\n        return left ?? right\n    }\n    <\/pre>\n<h3>Code Explanation<\/h3>\n<p>The above code works as follows:<\/p>\n<ul>\n<li>If the root node is nil, it returns <code>nil<\/code>.<\/li>\n<li>If the current node is one of the nodes being searched for, it returns that node.<\/li>\n<li>It recursively calls the <code>lowestCommonAncestor<\/code> function to find the lowest common ancestor in the left subtree. It does the same for the right subtree.<\/li>\n<li>If both the left and right calls result in non-nil, it means the current node is the lowest common ancestor, so it returns the current node.<\/li>\n<li>If not, it returns either the left or right result.<\/li>\n<\/ul>\n<h2>Time Complexity<\/h2>\n<p>The time complexity of this algorithm is O(N). N is the number of nodes in the tree, as we have to visit each node at least once, leading to a time complexity proportional to the maximum number of nodes.<\/p>\n<h2>Space Complexity<\/h2>\n<p>The space complexity of this algorithm is also O(H). H is the height of the tree, corresponding to the stack space used in recursive calls. In the worst case, if the tree is skewed to one side, it can be O(N).<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we explored how to solve the lowest common ancestor problem in a binary tree and how to implement it in Swift. This problem is a common topic in various technical interviews, so it is important to practice with multiple examples to enhance proficiency.<\/p>\n<h2>Frequently Asked Questions (FAQ)<\/h2>\n<h3>Question 1: Can we find LCA in a graph that is not a binary tree?<\/h3>\n<p>Yes, it is possible to find LCA in general graphs that are not binary trees, but it may require more complex algorithms depending on the case. For instance, methods like dynamic programming may be used.<\/p>\n<h3>Question 2: Are there other methods to solve the LCA problem?<\/h3>\n<p>There are several algorithms to find the lowest common ancestor. For example, using parent pointers or utilizing bitmasks, but one might choose methods with less preprocessing and space complexity.<\/p>\n<h3>Question 3: Can the LCA problem be extended?<\/h3>\n<p>Yes, there are problems that extend the LCA problem to find the lowest common ancestor for more than K nodes. These problems require more complex structures or algorithms, thus necessitating deeper understanding through practice.<\/p>\n<h2>In Conclusion<\/h2>\n<p>The lowest common ancestor problem requires a deep understanding of tree structures, making it very important for learning algorithms. It is necessary to practice solving various types of problems to enhance one&#8217;s understanding of this topic.<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This lecture will cover the Lowest Common Ancestor (LCA) problem. This problem involves finding the lowest common ancestor of two given nodes, a concept that is very useful in tree structures. It is particularly helpful in enhancing understanding of data structures and algorithms. Problem Description Write a function to find the lowest common ancestor of &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34856\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Swift Coding Test Course, Lowest Common Ancestor&#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":[129],"tags":[],"class_list":["post-34856","post","type-post","status-publish","format-standard","hentry","category-swift-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Swift Coding Test Course, Lowest Common Ancestor - \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\/34856\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swift Coding Test Course, Lowest Common Ancestor - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"This lecture will cover the Lowest Common Ancestor (LCA) problem. This problem involves finding the lowest common ancestor of two given nodes, a concept that is very useful in tree structures. It is particularly helpful in enhancing understanding of data structures and algorithms. Problem Description Write a function to find the lowest common ancestor of &hellip; \ub354 \ubcf4\uae30 &quot;Swift Coding Test Course, Lowest Common Ancestor&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34856\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:32:46+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:26:14+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\/34856\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34856\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Swift Coding Test Course, Lowest Common Ancestor\",\"datePublished\":\"2024-11-01T09:32:46+00:00\",\"dateModified\":\"2024-11-01T11:26:14+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34856\/\"},\"wordCount\":599,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Swift Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34856\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34856\/\",\"name\":\"Swift Coding Test Course, Lowest Common Ancestor - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:32:46+00:00\",\"dateModified\":\"2024-11-01T11:26:14+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34856\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34856\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34856\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Swift Coding Test Course, Lowest Common Ancestor\"}]},{\"@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":"Swift Coding Test Course, Lowest Common Ancestor - \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\/34856\/","og_locale":"ko_KR","og_type":"article","og_title":"Swift Coding Test Course, Lowest Common Ancestor - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"This lecture will cover the Lowest Common Ancestor (LCA) problem. This problem involves finding the lowest common ancestor of two given nodes, a concept that is very useful in tree structures. It is particularly helpful in enhancing understanding of data structures and algorithms. Problem Description Write a function to find the lowest common ancestor of &hellip; \ub354 \ubcf4\uae30 \"Swift Coding Test Course, Lowest Common Ancestor\"","og_url":"https:\/\/atmokpo.com\/w\/34856\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:32:46+00:00","article_modified_time":"2024-11-01T11:26:14+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\/34856\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34856\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Swift Coding Test Course, Lowest Common Ancestor","datePublished":"2024-11-01T09:32:46+00:00","dateModified":"2024-11-01T11:26:14+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34856\/"},"wordCount":599,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Swift Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34856\/","url":"https:\/\/atmokpo.com\/w\/34856\/","name":"Swift Coding Test Course, Lowest Common Ancestor - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:32:46+00:00","dateModified":"2024-11-01T11:26:14+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34856\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34856\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34856\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Swift Coding Test Course, Lowest Common Ancestor"}]},{"@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\/34856","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=34856"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34856\/revisions"}],"predecessor-version":[{"id":34857,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34856\/revisions\/34857"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34856"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34856"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34856"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}