Amazon Interview Question
Country: India
Some clarification : 100,70,90 imagine as a BST though the problem is not for a BST.then we have N(100) L(70) R(90).
O(n) means in almost one Tree traversal you should figure out the solution.
The algorithm will be as follows -
Maintain 2 list -> start_node_list
and end_node_list
For each node check if the pattern exist -> put the node in the start_node and put the end node in end_node_list.
Once all the nodes are traversed you will have a list of start nodes and end nodes.
now this problem reduces to finding the longest sequence of start and end nodes.
The algorithm is O(n|p|) = O(n)
First check at every node(we can do in order traversal) if the patterns exist.
If we find a pattern at any given node, we add that in array list
Lets define a new class
pair {
Node startnode
Node endnode
int length;}
Now when you find a pattern at a node say startnode to endnode.
Now adding part
if array list already have this startnode as any of the pair's endnode, increment the lenth of that pair by 1 and replace the endnode with new endnode.
else just add this new pair in array list
once done traverse the array list to find the max length.
this will be O(n+2m) n is no of nodes and m is number of sequences
so this is O(n)
Without even understanding the question people are posting their solution...
First of all the question is not clear.. someone explain the question first then we can think of the solutions
Take this as a BST (it will be easy to explain)
100,90,80,10,85,94,91,95,200,300,250.
Let p = LL
So S will be LL, LL, LL, LL, … problems simply reduces to finding longest length of only left traversal.
First get all nodes that occur as only left traversal
1. L1 = 100, 90, 80, 10.
2. L2 = 94, 91.
3. L3 = 300, 250.
Longest is L1,
Does each "L" or "R" traversal generate exactly one "p" one in the sequence? or do these "L" and "R" 's generate sequences of different lengths?
- someone December 20, 2011