Interview Question for Software Developers
- 0of 0 votes
AnswerGiven M nodes and at most one outgoing edge from any node. Given Q operations where an operation is either
- lifeenergy999 June 19, 2016 in India
i) 1 Z where Z represent the source node, print the terminal node if a coin travels through edges. In case, if node Z lies in a cycle, print LOOP. 1 is the operation type
ii) 2 Z where Z represents node for which the outgoing edge is removed and 2 is operation type.
Operations are performed in order in which they are given.
M <= 3*10^5, Q <= 3*10^5
Input
First line contains integer M.
Second line contains M integers, where ith integer represents outgoing edge from ith node. If outgoing edge is 0, that means there is no outgoing edge from this node.
Third line contains integer Q followed by Q lines where each line is either 1 Z, or 2 Z where Z is node number. Nodes are 1-indexed.
This question was asked in coding test. Can somebody please help me with this problem with the given constraints?| Report Duplicate | Flag | PURGE
Software Developer Algorithm
Got the solution. We can check for all the nodes whether there is cycle with that node. Consider the edges to be reversed, the problem turns out to be finding the root node for a node. Now, we need to calculate the start_time and end_time for all the nodes and we need to store the start_time, end_time, root_node for different components within a array. Now, given a node, we know the start_time, end_time for the node. We can do a binary search over that array to figure out the best fitting component(by taking max_value for a node for which start_time<=start_time for the given node) , which in turn gives us the root_node.
- lifeenergy999 June 19, 2016