title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
---|---|---|---|---|---|---|---|
Python 3 || 14 lines, w/ analysis || T/M: 1647 ms / 55.9 MB (100/100) | add-edges-to-make-degrees-of-all-nodes-even | 0 | 1 | Here\'s the analysis:\n\n- Applying one edge fixes exactly two odd edges. Therefore the only fixable graphs are those with either two or four odd nodes.\n\n- A graph with anything other than zero, two, or four odd nodes cannot be fixed; the answer in those cases is `False`.\n- Case 0: Obviously`True`.\n- Case 2: Suppose the nodes are *a* and *b*. i) If there\'s no edge between *a* and *b*, we connect them with an edge and return `True` ii) If there is an edgebetween *a* and *b* already, then we seek a node that does not share an edge with either *a* or *b*. If one exists, we return `True`.\n- Case 4: Added edges each must connect a pair of the four odd nodes, which can happen if and only if there exist such a pairing. There are three pairings to check.\n- If we exhaust the above possibilities, we return`False`.\n```\nclass Solution:\n def isPossible(self, n: int, edges: List[List[int]]) -> bool:\n\n dic = defaultdict(set) # <\u2013\u2013 Build the graph \n # \n for p,q in edges: # \n dic[p].add(q) # \n dic[q].add(p) # \n \n oddNodes = [node for node in dic # <\u2013\u2013 Determine the odd nodes\n if len(dic[node])%2] #\n \n m = len(oddNodes)\n\n if m == 0: return True # <\u2013\u2013 Case 0\n \n if m == 2: # <\u2013\u2013 Case 2\n\n a,b = oddNodes \n\n return (not {a} & dic[b] or # <\u2013\u2013 Case 2i\n not all({a,b} & dic[i]for i in dic)) # <\u2013\u2013 Case 2ii\n \n if m == 4: # <\u2013\u2013 Case 4\n a, b, c, d = oddNodes\n \n if (not(a in dic[b] or c in dic[d]) or # <\u2013\u2013 Find the pairings, if possible \n not(a in dic[c] or b in dic[d]) or\n not(a in dic[d] or b in dic[c])):\n return True\n\n return False # <\u2013\u2013 If nothing works, return False\n\n```\n[https://leetcode.com/problems/add-edges-to-make-degrees-of-all-nodes-even/submissions/861921730/](http://)\n\n- Python 3 || 14 lines, w/ analysis || T/M: 1647 ms / 55.9 MB (100/100) | 4 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.
Return `true` _if it is possible to make the degree of each node in the graph even, otherwise return_ `false`_._
The degree of a node is the number of edges connected to it.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2\],\[2,3\],\[3,4\],\[4,2\],\[1,4\],\[2,5\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding an edge.
Every node in the resulting graph is connected to an even number of edges.
**Example 2:**
**Input:** n = 4, edges = \[\[1,2\],\[3,4\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding two edges.
**Example 3:**
**Input:** n = 4, edges = \[\[1,2\],\[1,3\],\[1,4\]\]
**Output:** false
**Explanation:** It is not possible to obtain a valid graph with adding at most 2 edges.
**Constraints:**
* `3 <= n <= 105`
* `2 <= edges.length <= 105`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `ai != bi`
* There are no repeated edges. | null |
Python Hard | add-edges-to-make-degrees-of-all-nodes-even | 0 | 1 | ```\nclass Solution:\n def isPossible(self, n: int, edges: List[List[int]]) -> bool:\n \'\'\'\n You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.\n\nReturn true if it is possible to make the degree of each node in the graph even, otherwise return false.\n \n \'\'\'\n \n d = defaultdict(set)\n \n for start, end in edges:\n d[start].add(end)\n d[end].add(start)\n \n \n options = []\n \n for v in d:\n if len(d[v]) % 2 == 1:\n options.append(v)\n \n if len(options) > 4:\n return False\n \n \n if len(options) == 4:\n N = len(options)\n\n valid = [0] * N\n\n @cache\n def tryi(i, used):\n if sum(valid) == N:\n return True\n\n if i == N:\n return False\n\n if valid[i]:\n return tryi(i + 1, used)\n\n if not used:\n return False\n\n\n for j in range(i + 1, N):\n if options[j] not in d[options[i]] and not valid[j]:\n valid[j] = 1\n valid[i] = 1\n if tryi(i + 1, used - 1):\n return True\n valid[j] = 0\n valid[i] = 0\n\n return False\n \n \n return tryi(0, 2)\n \n \n if len(options) == 2:\n if options[0] not in d[options[1]]:\n return True\n \n \n for i in range(1, n + 1):\n if i in options:\n continue\n if options[0] not in d[i] and options[1] not in d[i]:\n return True\n \n \n return False\n \n \n if len(options) == 3:\n return False\n \n return True\n \n \n \n \n \n \n \n \n``` | 0 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.
Return `true` _if it is possible to make the degree of each node in the graph even, otherwise return_ `false`_._
The degree of a node is the number of edges connected to it.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2\],\[2,3\],\[3,4\],\[4,2\],\[1,4\],\[2,5\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding an edge.
Every node in the resulting graph is connected to an even number of edges.
**Example 2:**
**Input:** n = 4, edges = \[\[1,2\],\[3,4\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding two edges.
**Example 3:**
**Input:** n = 4, edges = \[\[1,2\],\[1,3\],\[1,4\]\]
**Output:** false
**Explanation:** It is not possible to obtain a valid graph with adding at most 2 edges.
**Constraints:**
* `3 <= n <= 105`
* `2 <= edges.length <= 105`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `ai != bi`
* There are no repeated edges. | null |
Python & C++ | O(mn) time | Find common ancestor with explanation | cycle-length-queries-in-a-tree | 0 | 1 | The description of the problem is quite long but you basically need to find to the common ancestor of nodes in each query.\nThe problem is very similar to https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/\n\nHere we do not even need to track parents for each child (and use dict as in the similar problem) because we know that each child is either `2 * val` or `2 * val + 1`. So, for each query we try to find an ancestor by dividing by 2 the node with larger value. Meanwhile, we also track the number of steps to reach the ancestor.\n\n*Time complexity*: `O(mn)`, where m is the size of `queries`\n*Space complexity*: `O(m)` to store the result\n\n**Python**\n\n```\nclass Solution:\n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n ans = []\n for p, q in queries:\n path = 0\n while p != q:\n path += 1\n if p > q:\n p >>= 1\n else:\n q >>= 1\n ans.append(path + 1) # to account for path between p and q\n return ans\n```\n\n**C++**\n\n```\nclass Solution {\npublic:\n vector<int> cycleLengthQueries(int n, vector<vector<int>>& queries) {\n vector<int> res(queries.size(), 0);\n for (int i = 0; i < (int) queries.size(); ++i) {\n int p = queries[i][0];\n int q = queries[i][1];\n int path = 0;\n while (p != q) {\n ++path;\n if (p > q)\n p >>= 1;\n else\n q >>= 1;\n }\n res[i] = path + 1; // to account for path between p and q\n }\n return res;\n }\n};\n``` | 3 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
Easy python Solution. | cycle-length-queries-in-a-tree | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n res=[]\n for x,y in queries:\n ans=1\n while x!=y:\n if x>y:\n x//=2\n else:\n y//=2\n ans+=1\n res.append(ans)\n \n return res\n``` | 1 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
[C++|Java|Python3] climbing up | cycle-length-queries-in-a-tree | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/af6e415cd101768ea8743ea9e4d22d788c9461c3) for solutions of weekly 324. \n\n**Intuition**\nSince this is a complete tree, it is guaranteed to be shallow. We can compute the result of each query in a brute-force approach by visiting the parent of the two nodes. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic: \n\tvector<int> cycleLengthQueries(int n, vector<vector<int>>& queries) {\n vector<int> ans; \n for (auto& q : queries) {\n unordered_map<int, int> dist; \n for (int u = q[0], d = 0; u; u /= 2) \n dist[u] = ++d; \n for (int v = q[1], d = 0; v; v /= 2, ++d) \n if (dist.count(v)) {\n ans.push_back(d + dist[v]); \n break; \n }\n }\n return ans; \n }\n};\n```\n**Java**\n```\nclass Solution {\n public int[] cycleLengthQueries(int n, int[][] queries) {\n int sz = queries.length; \n\t\tint[] ans = new int[sz]; \n\t\tfor (int i = 0; i < sz; ++i) {\n\t\t\tHashMap<Integer, Integer> dist = new HashMap(); \n\t\t\tfor (int u = queries[i][0], d = 0; u > 0; u /= 2) \n\t\t\t\tdist.put(u, ++d); \n\t\t\tfor (int v = queries[i][1], d = 0; v > 0; v /= 2, ++d) \n\t\t\t\tif (dist.containsKey(v)) {\n\t\t\t\t\tans[i] = d + dist.get(v); \n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t}\n\t\treturn ans; \n }\n}\n```\n**Python3**\n```\nclass Solution: \n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n ans = []\n for u, v in queries: \n dist = {}\n d = 0\n while u: \n dist[u] = (d := d+1)\n u //= 2\n d = 0 \n while v not in dist: \n d += 1\n v //= 2\n ans.append(d + dist[v])\n return ans \t\n```\n**Complexity**\nTime `O(NlogN)`\nSpace `O(logN)` | 1 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
[Python3] Lowest Common Ancestor | cycle-length-queries-in-a-tree | 0 | 1 | # Code\n```\nclass Solution:\n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n ans = []\n for a, b in queries:\n path_a, path_b = self.getPath(a), self.getPath(b)\n set_a, set_b = set(path_a), set(path_b)\n cnt = 0\n for num in path_a:\n if num not in set_b:\n cnt += 1\n for num in path_b:\n if num not in set_a:\n cnt += 1\n ans.append(cnt + 1)\n return ans\n \n def getPath(self, num):\n ans = []\n while num:\n ans.append(num)\n num //= 2\n return ans\n``` | 1 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
[python3] lca sol for reference | cycle-length-queries-in-a-tree | 0 | 1 | T: O(H * Q)\nS: O(Q)\n\nH = log2(n + 1)\n\n```\nclass Solution:\n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n ans = []\n for s, e in queries: \n p = s\n q = e\n a = 0\n \n while p != q: \n while p > q: \n p = p//2\n a += 1\n while q > p:\n q = q//2\n a += 1\n \n ans.append(a+1)\n \n return ans | 1 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
Python 3 || 9 lines, w/ brief explanation || T/M: 81%/91% | cycle-length-queries-in-a-tree | 0 | 1 | Here\'s the plan:\n- The parent of node`n`is `n//2`. \n- Given two query nodes`a`and`b`, we can select the larger of`a`or`b`and int-divide it by two in each step. We count these steps, and we stop when `a`and`b`are equal.\n- We initialize the step count`moves`as 1 to account for the edge between the nodes given in the query.\n\n```\nclass Solution:\n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n ans = []\n\n for a, b in queries:\n moves = 1\n\n while a != b:\n if a > b: a//= 2\n else : b//= 2\n\n moves+= 1\n\n ans.append(moves) \n \n return ans\n```\n[https://leetcode.com/problems/cycle-length-queries-in-a-tree/submissions/862015999/](http://)\n\n\nI could be wrong, but I think that time is *O*(*N*log*N*) and space is *O*(*N*). | 5 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
[Python | Time & Space Beats 100%] O(1) Time Complexity for Each Query, Super Easy Implementation. | cycle-length-queries-in-a-tree | 0 | 1 | # Intuition\nBinary Encoding: Given the context of this question, actually its much more easier to understand it in binary encoding:\n\nFor example, node #6, can be written in binary as 0b110, and can be interprated as 1(right) -> 1(right) -> 0(left). Following this intuition, given two nodes, for example #12(0b1100) and #13(0b1101), their common ancestor is the longest commen prefix in their binary encoding, which is 0b110 -> #6! \n\nSee? You can easily get the common ancestor of any two of the nodes by simply compare their binary encoding and get the longest commen prefix. Knowing where their LCA is, the rest of the steps are then obvious.\n\n\n# Complexity\nConsidering the maximum length of the binary encoding is about 30, for each query, their time complexity is simply O(1).\n- Time complexity: O(M) \n- Space complexity: O(M)\n\n# Code\n```\nclass Solution:\n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n res = []\n for a, b in queries:\n bin_a = bin(a)[2:]\n bin_b = bin(b)[2:]\n \n i = 0\n while i < len(bin_a) and i < len(bin_b) and bin_a[i] == bin_b[i]:\n i += 1\n res.append(len(bin_a) + len(bin_b) - 2 * i + 1)\n \n return res\n \n``` | 1 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
Simple O(n) Single-pass solution | cycle-length-queries-in-a-tree | 0 | 1 | Given the properties of the tree in question, node with value **n** has parent value **floor(n/2)**. This can be used to traverse upwards in the tree from both nodes (while keeping track of distance traveled) until a common ancestor is found. This distance will represent the length of the cycle less the single edge connecting the two nodes.\n\n```\nclass Solution:\n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n res = []\n for q in queries:\n a,b,d = q[0], q[1], 0\n\n # find common ancestor\n while a != b:\n if a > b:\n a = floor(a/2)\n else:\n b = floor(b/2)\n d += 1\n res.append(d + 1)\n return res\n \n\n``` | 0 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
easy | cycle-length-queries-in-a-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def cycleLengthQueries(self, n: int, q: List[List[int]]) -> List[int]:\n def get(a,b):\n ans = 0 \n while a!=b :\n if a > b :\n ans+=1\n a=a//2\n if a<b :\n ans+=1\n b=b//2\n return ans\n ans = []\n for x in q :\n ans.append(1+get(x[0],x[1]))\n return ans\n\n\n \n \n``` | 0 | You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the value `2 * val`, and
* The right node has the value `2 * val + 1`.
You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, solve the following problem:
1. Add an edge between the nodes with values `ai` and `bi`.
2. Find the length of the cycle in the graph.
3. Remove the added edge between nodes with values `ai` and `bi`.
**Note** that:
* A **cycle** is a path that starts and ends at the same node, and each edge in the path is visited only once.
* The length of a cycle is the number of edges visited in the cycle.
* There could be multiple edges between two nodes in the tree after adding the edge of the query.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** n = 3, queries = \[\[5,3\],\[4,7\],\[2,3\]\]
**Output:** \[4,5,3\]
**Explanation:** The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes \[5,2,1,3\]. Thus answer to the first query is 4. We delete the added edge and process the next query.
- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes \[4,2,1,3,7\]. Thus answer to the second query is 5. We delete the added edge and process the next query.
- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes \[2,1,3\]. Thus answer to the third query is 3. We delete the added edge.
**Example 2:**
**Input:** n = 2, queries = \[\[1,2\]\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.
- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes \[2,1\]. Thus answer for the first query is 2. We delete the added edge.
**Constraints:**
* `2 <= n <= 30`
* `m == queries.length`
* `1 <= m <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= 2n - 1`
* `ai != bi` | null |
Subsets and Splits