![]() |
VOOZH | about |
Given two integer values (i and j) as input representing two nodes of a special binary tree. The special binary tree has this property that the root node's value is always 1 and for every node, its left child will be the node's value * 3, and the right child will be ( node's value * 3) + 1. The given integer values exist in the tree then find the minimum steps required to reach the other node. By moving one step you can either move one level up or go one level down.
Examples:
Input: i = 1, j = 3
Output: 1
Explanation: The tree for the above input will be1
/ \
3 4The difference between levels of 1 and 3 is 1 so it will take 1 step.
Input: i = 1, j = 39
Output: 3
Explanation: The tree for the above input will be1
/ \
3 4
/ \ / \
9 10 12 13
/ \ / \ / \ / \
27 28 30 31 36 37 38 39Here the difference between level of 1 and 39 is 3 so it will take 3 steps.
Intuition: To solve the problem follow the below idea:
Start generating the tree with the mentioned property until we encounter both the nodes and as soon as we found both the nodes then find level of both nodes and return absolute difference between them.
Approach: Follow the below steps:
We will use a 2D Vector for constructing the binary tree and the row of 2D vector will represent level of current row so it will be easy for further calculation. Initialize three variables ithRow = -1 , jthRow = -1 and row = 0, along with a 2D vector arr with value 1. Now run a while loop till ithRow == - 1 and jthRow == -1 and repeat the below mentioned steps for every iteration. NOTE: i and j are input values.
Below Code is the implementation of above approach in CPP.
1
Time Complexity: O(i*j)
Auxiliary Space: O((max(i, j)/3)^2)