{"id":355712,"date":"2024-05-20T23:14:31","date_gmt":"2024-05-20T23:14:31","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=355712"},"modified":"-0001-11-30T00:00:00","modified_gmt":"2024-05-20T23:14:31","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=355712","title":{"rendered":"<span>LeetCode, Hard++ (Acceptance 24%, Latest): 2867. Count Valid Paths in a Tree. DFS. O(n). Swift<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<h3>Description<\/h3>\n<p>There is an undirected tree with n nodes labeled from 1 to n. You are given the integer n and a 2D integer array edges of length n &#8212; 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree.<\/p>\n<p>Return the number of valid paths in the tree.<\/p>\n<p>A path (a, b) is valid if there exists exactly one prime number among the node labels in the path from a to b.<\/p>\n<p>Note that:<br \/>The path (a, b) is a sequence of distinct nodes starting with node a and ending with node b such that every two adjacent nodes in the sequence share an edge in the tree.<br \/>Path (a, b) and path (b, a) are considered the same and counted only once.<\/p>\n<p>Example 1:<\/p>\n<pre><code>Input: n = 5, edges = [[1,2],[1,3],[2,4],[2,5]] Output: 4 Explanation: The pairs with exactly one prime number on the path between them are:  - (1, 2) since the path from 1 to 2 contains prime number 2.  - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (2, 4) since the path from 2 to 4 contains prime number 2. It can be shown that there are only 4 valid paths.<\/code><\/pre>\n<p>Example 2:<\/p>\n<pre><code>Input: n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]] Output: 6 Explanation: The pairs with exactly one prime number on the path between them are:  - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (1, 6) since the path from 1 to 6 contains prime number 3. - (2, 4) since the path from 2 to 4 contains prime number 2. - (3, 6) since the path from 3 to 6 contains prime number 3. It can be shown that there are only 6 valid paths.<\/code><\/pre>\n<p><strong>Constraints<\/strong>:<br \/>1 &lt;= n &lt;= 10^5<br \/>edges.length == n &#8212; 1<br \/>edges[i].length == 2<br \/>1 &lt;= u(i), v(i) &lt;= n<br \/>The input is generated such that edges represent a valid tree.<\/p>\n<h3>Intuition<\/h3>\n<p>The intuition is to employ a depth-first search (DFS) approach through the tree.<\/p>\n<h3>Approach<\/h3>\n<p>During each step in the traversal, we perform the following key calculations:<\/p>\n<ol>\n<li>\n<p>Determine the path that ends at the current node.<\/p>\n<\/li>\n<li>\n<p>Compute two different subtree paths that traverse the current node.<\/p>\n<\/li>\n<li>\n<p>Maintain an array that keeps track of the cases where paths contain either 0 or 1 prime number.<\/p>\n<\/li>\n<\/ol>\n<p>This method allows us to efficiently count the valid paths in the tree while considering the presence of prime numbers.<\/p>\n<h3>Complexity<\/h3>\n<ul>\n<li>\n<p>Time complexity: O(n)<\/p>\n<\/li>\n<li>\n<p>Space complexity: O(n)<\/p>\n<\/li>\n<\/ul>\n<h3>Code (Swift)<\/h3>\n<pre><code class=\"swift\">class Solution {     func countPaths(_ n: Int, _ edges: [[Int]]) -> Int {         var ans = 0         var primes = Array(repeating: 1, count: n + 5)          primes[1] = 0         for i in 2...Int(sqrt(Double(n + 5))) {             if primes[i] == 0 {                 continue             }             for j in stride(from: i * i, to: primes.count, by: i) {                 primes[j] = 0             }         }          var adjList = Array(repeating: [Int](), count: n + 1)         for edge in edges {             adjList[edge[0]].append(edge[1])             adjList[edge[1]].append(edge[0])         }          func dfs(_ curr: Int, _ parent: Int, _ adjList: [[Int]]) -> [Int] {             var count = [0, 0]             let isPrime = primes[curr] == 1              for child in adjList[curr] {                 if child == parent {                     continue                 }                 let next = dfs(child, curr, adjList)                 if isPrime {                     \/\/ Path ends at curr                     ans += next[0]                     \/\/ curr is conduit for path                     ans += count[1] * next[0]                      count[1] += next[0]                 } else {                     \/\/ Ends at curr                     ans += next[1]                     \/\/ curr is conduit for path                     ans += count[0] * next[1]                     ans += count[1] * next[0]                      count[0] += next[0]                     count[1] += next[1]                 }             }              count[isPrime ? 1 : 0] += 1             return count         }          dfs(1, -1, adjList)         return ans     } } <\/code><\/pre>\n<p>Sources:\u00a0<a href=\"https:\/\/github.com\/sergeyleschev\/leetcode-swift\/blob\/main\/2501-3000\/2867.%20Count%20Valid%20Paths%20in%20a%20Tree.swift\" rel=\"noopener noreferrer nofollow\"><u>Github<\/u><\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/763072\/\"> https:\/\/habr.com\/ru\/articles\/763072\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<h3>Description<\/h3>\n<p>There is an undirected tree with n nodes labeled from 1 to n. You are given the integer n and a 2D integer array edges of length n &#8212; 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree.<\/p>\n<p>Return the number of valid paths in the tree.<\/p>\n<p>A path (a, b) is valid if there exists exactly one prime number among the node labels in the path from a to b.<\/p>\n<p>Note that:<br \/>The path (a, b) is a sequence of distinct nodes starting with node a and ending with node b such that every two adjacent nodes in the sequence share an edge in the tree.<br \/>Path (a, b) and path (b, a) are considered the same and counted only once.<\/p>\n<p>Example 1:<\/p>\n<pre><code>Input: n = 5, edges = [[1,2],[1,3],[2,4],[2,5]] Output: 4 Explanation: The pairs with exactly one prime number on the path between them are:  - (1, 2) since the path from 1 to 2 contains prime number 2.  - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (2, 4) since the path from 2 to 4 contains prime number 2. It can be shown that there are only 4 valid paths.<\/code><\/pre>\n<p>Example 2:<\/p>\n<pre><code>Input: n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]] Output: 6 Explanation: The pairs with exactly one prime number on the path between them are:  - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (1, 6) since the path from 1 to 6 contains prime number 3. - (2, 4) since the path from 2 to 4 contains prime number 2. - (3, 6) since the path from 3 to 6 contains prime number 3. It can be shown that there are only 6 valid paths.<\/code><\/pre>\n<p><strong>Constraints<\/strong>:<br \/>1 &lt;= n &lt;= 10^5<br \/>edges.length == n &#8212; 1<br \/>edges[i].length == 2<br \/>1 &lt;= u(i), v(i) &lt;= n<br \/>The input is generated such that edges represent a valid tree.<\/p>\n<h3>Intuition<\/h3>\n<p>The intuition is to employ a depth-first search (DFS) approach through the tree.<\/p>\n<h3>Approach<\/h3>\n<p>During each step in the traversal, we perform the following key calculations:<\/p>\n<ol>\n<li>\n<p>Determine the path that ends at the current node.<\/p>\n<\/li>\n<li>\n<p>Compute two different subtree paths that traverse the current node.<\/p>\n<\/li>\n<li>\n<p>Maintain an array that keeps track of the cases where paths contain either 0 or 1 prime number.<\/p>\n<\/li>\n<\/ol>\n<p>This method allows us to efficiently count the valid paths in the tree while considering the presence of prime numbers.<\/p>\n<h3>Complexity<\/h3>\n<ul>\n<li>\n<p>Time complexity: O(n)<\/p>\n<\/li>\n<li>\n<p>Space complexity: O(n)<\/p>\n<\/li>\n<\/ul>\n<h3>Code (Swift)<\/h3>\n<pre><code class=\"swift\">class Solution {     func countPaths(_ n: Int, _ edges: [[Int]]) -> Int {         var ans = 0         var primes = Array(repeating: 1, count: n + 5)          primes[1] = 0         for i in 2...Int(sqrt(Double(n + 5))) {             if primes[i] == 0 {                 continue             }             for j in stride(from: i * i, to: primes.count, by: i) {                 primes[j] = 0             }         }          var adjList = Array(repeating: [Int](), count: n + 1)         for edge in edges {             adjList[edge[0]].append(edge[1])             adjList[edge[1]].append(edge[0])         }          func dfs(_ curr: Int, _ parent: Int, _ adjList: [[Int]]) -> [Int] {             var count = [0, 0]             let isPrime = primes[curr] == 1              for child in adjList[curr] {                 if child == parent {                     continue                 }                 let next = dfs(child, curr, adjList)                 if isPrime {                     \/\/ Path ends at curr                     ans += next[0]                     \/\/ curr is conduit for path                     ans += count[1] * next[0]                      count[1] += next[0]                 } else {                     \/\/ Ends at curr                     ans += next[1]                     \/\/ curr is conduit for path                     ans += count[0] * next[1]                     ans += count[1] * next[0]                      count[0] += next[0]                     count[1] += next[1]                 }             }              count[isPrime ? 1 : 0] += 1             return count         }          dfs(1, -1, adjList)         return ans     } } <\/code><\/pre>\n<p>Sources:\u00a0<a href=\"https:\/\/github.com\/sergeyleschev\/leetcode-swift\/blob\/main\/2501-3000\/2867.%20Count%20Valid%20Paths%20in%20a%20Tree.swift\" rel=\"noopener noreferrer nofollow\"><u>Github<\/u><\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/763072\/\"> https:\/\/habr.com\/ru\/articles\/763072\/<\/a><br \/><\/br><\/br><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-355712","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/355712","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=355712"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/355712\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=355712"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=355712"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=355712"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}