Shortest Distance

Easy
0/40
Average time to solve is 10m
profile
Contributed by
6 upvotes
Asked in companies
MakeMyTripDunzoBlackrock

Problem statement

You have been given a Binary Search Tree and two keys 'NODE1' and 'Node2' in it.

Your task is to find the shortest distance between two nodes with the given two keys. It may be assumed that both keys exist in BST.

Example:

alttext

For the above BST:
‘NODE1’ = 6, ‘NODE2’ = 14

Distance between 6 and 14 = (Number of nodes in the path from 6 to 14) + 1.
So the path from 6 to 14 is : ( 6 -> 3 -> 8 -> 10 -> 14).

Distance between 6 and 14 = 3 ( i.e. 3, 8, 10 are in path) + 1 = 4.
Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases. Then each test case follows.

The first line of input contains the elements of the tree in the level order form separated by a single space. 
If any node does not have a left or right child, take -1 in its place. Refer to the example below.

The second line of each test case contains two space-separated integers, ‘NODE1’ and ‘NODE2’, denoting the keys of the two given nodes.
Example:
Elements are in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 in its place.

For example, the input for the tree (not a BST) depicted in the below image would be :

input

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :
Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.

The input ends when all nodes at the last level are null (-1).
Output Format:
For each test case, return an integer denoting the distance between two keys, i.e., ‘NODE1’ and ‘NODE2’ in the given BST.
Note:
You do not need to print anything; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10^2
1 <= N <= 10^3 
1 <= Node.data <= 10^9

Where 'N' denotes the number of nodes in the BST and 'Node.data' represents the keys of nodes in BST.
The keys ‘NODE1’ and ‘NODE2’ are present in the given BST.

Time Limit: 1 sec
Sample Input 1:
2
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
6 10
5 2 12 1 -1 -1 16 -1 -1 -1 -1
1 16
Sample Output 1:
3
4
Explanation For Sample Input 1:
For the first test case :

sample1

For the above BST:
‘NODE1’ = 6, ‘NODE2’ = 10   
Distance between 6 and 10 = (Number of nodes in the path from 6 to 10) + 1.
So the path from 6 to 10 is : ( 6 -> 5 -> 8 -> 10).

Distance between 6 and 10 = 2 ( i.e. 5, 8 are in path) + 1 = 3.

For the second test case :

sample2

For the above BST:
‘NODE1’ = 1, ‘NODE2’ = 16    
Distance between 1 and 16 = (Number of nodes in the path from 1 to 16) + 1.
So the path from 1 to 16 is : ( 1 -> 2 -> 5 -> 12 -> 16).

Distance between 1 and 16 = 3 ( i.e. 2, 5, 12 are in path) + 1 = 4.
Sample Input 2:
2
5 3 8 1 -1 -1 -1 -1 2 -1 -1
2 8
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
2 7
Sample Output 2:
4
3
Hint

Try to find the lowest common ancestor (LCA) of ‘NODE1’ and ‘NODE2’.

Approaches (2)
LCA

Lowest common ancestor: Let ‘T’ be a rooted tree. The lowest common ancestor of the two nodes, ‘NODE1’ and ‘NODE2’, is the lowest node in ‘T’ with both ‘NODE1’ and ‘NODE2’ as its descendants (here, a node can be a descendant of itself).
 

We store the path from ‘ROOT’ to ‘NODE1’ in ‘PATH1’ and ‘ROOT’ to ‘NODE2’ in ‘PATH2’. Iterate the arrays ‘PATH1’ and ‘PATH2’ until they have the same values, the LCA will be the node just before the mismatch. The following function finds the path from ‘ROOT’ to the node with the given ‘KEY’ and stores it in the array ‘PATH’ (passed by reference).

 

‘Boolean pathFromRoot(BinaryTreeNode ROOT, array PATH, integer KEY)’:

  • If ‘ROOT’ is ‘NULL’, then:
    • Return ‘FALSE’ (Base condition).
  • ‘path.append(ROOT->DATA)’. Append the key at the ‘ROOT’ node to ‘PATH’.
  • If ‘ROOT->DATA’ is equal to ‘KEY’, then we can stop the search for ‘KEY’:
    • Return ‘TRUE’.
  • If (‘pathFromRoot(ROOT->LEFT, PATH, KEY)’ is ‘TRUE’) or (‘pathFromRoot(ROOT->RIGHT, PATH, KEY)’ is ‘TRUE’), then we can stop the search for ‘KEY’ as the subtree at ‘ROOT’ contains the node with the given ‘KEY’:
    • Return ‘TRUE’.
  • ‘path.pop_back()’. Remove the last element of ‘PATH’ (i.e., ‘ROOT->DATA’) as the node with given ‘KEY’ is not present in the subtree at ‘ROOT’.
  • Return ‘FALSE’.

 

The shortest distance between ‘NODE1’ and ‘NODE2’ = (Distance from ‘LCA’ to ‘NODE1’) + (Distance from ‘LCA’ to ‘NODE2’).
 

ALGORITHM:

  • Create two integer arrays ‘PATH1’ and ‘PATH2’ to store the path from ‘ROOT’ to ‘NODE1’ and ‘ROOT’ to ‘NODE2’, respectively.
  • ‘pathFromRoot(ROOT, PATH1, NODE1)’. Store the path from ‘ROOT’ to ‘NODE1’ in the array ‘PATH1’.
  • ‘pathFromRoot(ROOT, PATH2, NODE2)’. Store the path from ‘ROOT’ to ‘NODE2’ in the array ‘PATH2’.
  • Set ‘i = 0’. Use it to find the first index where ‘PATH1’ and ‘PATH2’ are different.
  • Run a loop until (‘i < PATH1.size()’) and (‘i < PATH2.size()’):
    • If ‘PATH1[i]’ is not equal to ‘PATH2[i]’, then ‘i - 1’ is the index of the LCA of ‘NODE1’ and ‘NODE2’.:
      • Break the loop.
  • Set ‘DIST1 = PATH1.size() - i’. This is the distance of ‘NODE1’ from ‘LCA’.
  • Set ‘DIST2 = PATH2.size() - i’. This is the distance of ‘NODE2’ from ‘LCA’.
  • Return ‘DIST1 + DIST2’ as the answer.
Time Complexity

O(N), where ‘N’ is the number of nodes in the given BST.
 

To find the path from ‘ROOT’ to ‘NODE1’ and ‘ROOT’ to ‘NODE2’ we may have to traverse the entire BST. We traverse the arrays ‘PATH1’ and ‘PATH2’ which may store ‘O(N)’ elements. Thus, the time complexity is ‘O(N)’.

Space Complexity

O(N), where ‘N’ is the number of nodes in the given BST.


The recursion stack used for the function ‘pathfromRoot’ stores ‘O(N)’ elements. The arrays ‘PATH1’ and ‘PATH2’ also store ‘O(N)’ elements. Thus, the space complexity is ‘O(N)’.

Code Solution
(100% EXP penalty)
Shortest Distance
Full screen
Console