![]() |
VOOZH | about |
Given an unweighted and undirected graph consisting of N nodes and two integers a and b. The edge between any two nodes exists only if the bit difference between them is 2, the task is to find the length of the shortest path between the nodes a and b. If a path does not exist between the nodes a and b, then print -1.
Examples:
Input: N = 15, a = 15, b = 3
Output: 1
Explanation: a = 15 = (1111)2 and b = 3 = (0011)2. The bit difference between 15 and 3 is 2. Therefore, there is a direct edge between 15 and 3. Hence, length of the shortest path is 1.Input: N = 15, a = 15, b = 2
Output: -1
Explanation: a = 15 = (1111)2 and b= 2 = (0010)2. The bit difference between 15 and 2 is 3. As the bit difference can only be 2, it is impossible to reach 15
from 2.
Naive Approach: The simplest approach to solve this problem is to first construct the graph using the given conditions, then find the shortest path between the nodes using a and b using bfs by considering a as the source node of the graph.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach:The problem can be solved by observing that the sum of bit differences between any two nodes must be a factor 2 and their shortest distance must be half of that sum. Follow the steps given below to understand the approach:
Below is the implementation of the above approach:
1
Time Complexity: O(log2(N)
Auxiliary Space: O(1)