Skip to content

Practice Cycle Length Queries in a Tree

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#2509
LeetCode Problem

Cycle Length Queries in a Tree

Problem Statement

The complete binary tree has nodes 1 through 2^n - 1. Node v has children 2v and 2v + 1 whenever those labels exist. For each independent [a,b] query, add one extra edge between those nodes, count the edges in the resulting cycle, then remove the added edge. Parallel edges are allowed, so joining already adjacent nodes creates a two-edge cycle. Return lengths in query order.

Source: Cycle Length Queries in a Tree on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
n = 3, queries = [[5,3],[4,7],[2,3]]
Output
[4,5,3]

# Example 2

Input
n = 2, queries = [[1,2]]
Output
[2]

Constraints

2 <= n <= 30
m == queries.length
1 <= m <= 10^5
queries[i].length == 2
1 <= ai, bi <= 2^n - 1
ai != bi

Related LeetCode Problems

Practice more problems similar to Cycle Length Queries in a Tree.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.