Tap here to switch tabs
Problem
Submissions

Problem: Cycle Length Queries in a Tree

med
30 min
Try to solve the Cycle Length Queries in a Tree problem.

Statement

You are given an integer n representing a complete binary tree containing 2n−12^n - 1 nodes. The root node is labeled 11, and each node with value val has a left child labeled 2imesextval2 imes ext{val} and a right child labeled 2imesextval+12 imes ext{val} + 1.

You are also given a 22D integer array queries of size m, where queries[i] =[ai,bi]= [a_i, b_i]. For each query, an undirected edge is added between node aia_i and node bib_i, creating a cycle.

Return an integer array ans of length m, where ans[i] is the number of nodes in the cycle formed during the iextthi^{ ext{th}} query.

Note: Queries are processed independently. The edge added in a query is removed before moving to the next query.

Constraints:

  • 2≤2 \leq n ≤30\leq 30

  • m ==== queries.length

  • 1≤1 \leq m ≤105\leq 10^5

  • queries[i].length ==2== 2

  • 1≤ai,bi≤2n−11 \leq a_i, b_i \leq 2^n - 1

  • ai≠bia_i \neq b_i

⋮
Tap here to switch tabs
Problem
Submissions

Problem: Cycle Length Queries in a Tree

med
30 min
Try to solve the Cycle Length Queries in a Tree problem.

Statement

You are given an integer n representing a complete binary tree containing 2n−12^n - 1 nodes. The root node is labeled 11, and each node with value val has a left child labeled 2imesextval2 imes ext{val} and a right child labeled 2imesextval+12 imes ext{val} + 1.

You are also given a 22D integer array queries of size m, where queries[i] =[ai,bi]= [a_i, b_i]. For each query, an undirected edge is added between node aia_i and node bib_i, creating a cycle.

Return an integer array ans of length m, where ans[i] is the number of nodes in the cycle formed during the iextthi^{ ext{th}} query.

Note: Queries are processed independently. The edge added in a query is removed before moving to the next query.

Constraints:

  • 2≤2 \leq n ≤30\leq 30

  • m ==== queries.length

  • 1≤1 \leq m ≤105\leq 10^5

  • queries[i].length ==2== 2

  • 1≤ai,bi≤2n−11 \leq a_i, b_i \leq 2^n - 1

  • ai≠bia_i \neq b_i