{ "data": { "question": { "questionId": "2597", "questionFrontendId": "2509", "boundTopicId": null, "title": "Cycle Length Queries in a Tree", "titleSlug": "cycle-length-queries-in-a-tree", "content": "

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:

\n\n\n\n

You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each query, solve the following problem:

\n\n
    \n\t
  1. Add an edge between the nodes with values ai and bi.
  2. \n\t
  3. Find the length of the cycle in the graph.
  4. \n\t
  5. Remove the added edge between nodes with values ai and bi.
  6. \n
\n\n

Note that:

\n\n\n\n

Return an array answer of length m where answer[i] is the answer to the ith query.

\n\n

 

\n

Example 1:

\n\"\"\n
\nInput: n = 3, queries = [[5,3],[4,7],[2,3]]\nOutput: [4,5,3]\nExplanation: The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.\n- 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.\n- 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.\n- 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.\n
\n\n

Example 2:

\n\"\"\n
\nInput: n = 2, queries = [[1,2]]\nOutput: [2]\nExplanation: The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.\n- 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.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Hard", "likes": 173, "dislikes": 18, "isLiked": null, "similarQuestions": "[{\"title\": \"Populating Next Right Pointers in Each Node\", \"titleSlug\": \"populating-next-right-pointers-in-each-node\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Lowest Common Ancestor of a Binary Tree\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Path In Zigzag Labelled Binary Tree\", \"titleSlug\": \"path-in-zigzag-labelled-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "exampleTestcases": "3\n[[5,3],[4,7],[2,3]]\n2\n[[1,2]]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Tree", "slug": "tree", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Binary Tree", "slug": "binary-tree", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "class Solution {\npublic:\n vector cycleLengthQueries(int n, vector>& queries) {\n \n }\n};", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "class Solution {\n public int[] cycleLengthQueries(int n, int[][] queries) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "class Solution(object):\n def cycleLengthQueries(self, n, queries):\n \"\"\"\n :type n: int\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n ", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "class Solution:\n def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n ", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* cycleLengthQueries(int n, int** queries, int queriesSize, int* queriesColSize, int* returnSize){\n\n}", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "public class Solution {\n public int[] CycleLengthQueries(int n, int[][] queries) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {number} n\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar cycleLengthQueries = function(n, queries) {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "# @param {Integer} n\n# @param {Integer[][]} queries\n# @return {Integer[]}\ndef cycle_length_queries(n, queries)\n \nend", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "class Solution {\n func cycleLengthQueries(_ n: Int, _ queries: [[Int]]) -> [Int] {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "func cycleLengthQueries(n int, queries [][]int) []int {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "object Solution {\n def cycleLengthQueries(n: Int, queries: Array[Array[Int]]): Array[Int] = {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "class Solution {\n fun cycleLengthQueries(n: Int, queries: Array): IntArray {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Rust", "langSlug": "rust", "code": "impl Solution {\n pub fn cycle_length_queries(n: i32, queries: Vec>) -> Vec {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "class Solution {\n\n /**\n * @param Integer $n\n * @param Integer[][] $queries\n * @return Integer[]\n */\n function cycleLengthQueries($n, $queries) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "function cycleLengthQueries(n: number, queries: number[][]): number[] {\n\n};", "__typename": "CodeSnippetNode" }, { "lang": "Racket", "langSlug": "racket", "code": "(define/contract (cycle-length-queries n queries)\n (-> exact-integer? (listof (listof exact-integer?)) (listof exact-integer?))\n\n )", "__typename": "CodeSnippetNode" }, { "lang": "Erlang", "langSlug": "erlang", "code": "-spec cycle_length_queries(N :: integer(), Queries :: [[integer()]]) -> [integer()].\ncycle_length_queries(N, Queries) ->\n .", "__typename": "CodeSnippetNode" }, { "lang": "Elixir", "langSlug": "elixir", "code": "defmodule Solution do\n @spec cycle_length_queries(n :: integer, queries :: [[integer]]) :: [integer]\n def cycle_length_queries(n, queries) do\n\n end\nend", "__typename": "CodeSnippetNode" }, { "lang": "Dart", "langSlug": "dart", "code": "class Solution {\n List cycleLengthQueries(int n, List> queries) {\n\n }\n}", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"6.4K\", \"totalSubmission\": \"11.6K\", \"totalAcceptedRaw\": 6449, \"totalSubmissionRaw\": 11597, \"acRate\": \"55.6%\"}", "hints": [ "Find the distance between nodes “a” and “b”.", "distance(a, b) = depth(a) + depth(b) - 2 * LCA(a, b). Where depth(a) denotes depth from root to node “a” and LCA(a, b) denotes the lowest common ancestor of nodes “a” and “b”.", "To find LCA(a, b), iterate over all ancestors of node “a” and check if it is the ancestor of node “b” too. If so, take the one with maximum depth." ], "solution": null, "status": null, "sampleTestCase": "3\n[[5,3],[4,7],[2,3]]", "metaData": "{\n \"name\": \"cycleLengthQueries\",\n \"params\": [\n {\n \"type\": \"integer\",\n \"name\": \"n\"\n },\n {\n \"type\": \"integer[][]\",\n \"name\": \"queries\"\n }\n ],\n \"return\": {\n \"type\": \"integer[]\"\n }\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 17 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 17. Java 8 features such as lambda expressions and stream API can be used.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"c\": [\"C\", \"

Compiled with gcc 8.2 using the gnu11 standard.

\\r\\n\\r\\n

Your code is compiled with level one optimization (-O1). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n\\r\\n

For hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:

\\r\\n\\r\\n

1. Adding an item to a hash.\\r\\n

\\r\\nstruct hash_entry {\\r\\n    int id;            /* we'll use this field as the key */\\r\\n    char name[10];\\r\\n    UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n    HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

2. Looking up an item in a hash:\\r\\n

\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n    struct hash_entry *s;\\r\\n    HASH_FIND_INT(users, &user_id, s);\\r\\n    return s;\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

3. Deleting an item in a hash:\\r\\n

\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n
\\r\\n

\"], \"csharp\": [\"C#\", \"

C# 10 with .NET 6 runtime

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.1

\\r\\n\\r\\n

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.5.2.

\"], \"golang\": [\"Go\", \"

Go 1.17.6.

\\r\\n\\r\\n

Support https://godoc.org/github.com/emirpasic/gods library.

\"], \"python3\": [\"Python3\", \"

Python 3.10.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.3.10.

\"], \"rust\": [\"Rust\", \"

Rust 1.58.1

\\r\\n\\r\\n

Supports rand v0.6\\u00a0from crates.io

\"], \"php\": [\"PHP\", \"

PHP 8.1.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 4.5.4, Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2020 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"], \"racket\": [\"Racket\", \"

Run with Racket 8.3.

\"], \"erlang\": [\"Erlang\", \"Erlang/OTP 24.2\"], \"elixir\": [\"Elixir\", \"Elixir 1.13.0 with Erlang/OTP 24.2\"], \"dart\": [\"Dart\", \"

Dart 2.17.3

\\r\\n\\r\\n

Your code will be run directly without compiling

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }