Cycle Length Queries in a Tree — LeetCode 2509 Python Solution

HardTreeArrayBinary Tree
Problem
#2509
Reading time
3 min

The problem

You are given an integer n. There is a complete binary tree with 2n - 1 nodes.

Example

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.

Python solution

Python
class Solution:
    def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:
        ans = []
        for a, b in queries:
            t = 1
            while a != b:
                if a > b:
                    a >>= 1
                else:
                    b >>= 1
                t += 1
            ans.append(t)
        return ans

Complexity

MeasureComplexity
TimeO(n \times m), where m is the length of the `queries` array
SpaceO(h) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2509. Cycle Length Queries in a Tree is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Tree and Binary Tree.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2509. Cycle Length Queries in a Tree?
LeetCode 2509. Cycle Length Queries in a Tree is rated Hard on LeetCode.
What is the time complexity of LeetCode 2509. Cycle Length Queries in a Tree?
The Python solution on this page runs in O(n \times m), where m is the length of the `queries` array.
What is the space complexity of LeetCode 2509. Cycle Length Queries in a Tree?
The Python solution on this page uses O(h) auxiliary space.
What topics does LeetCode 2509. Cycle Length Queries in a Tree cover?
LeetCode 2509. Cycle Length Queries in a Tree is tagged Tree, Array and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview