Minimum time to return array to its original state after given modifications | Python implementation of above approach ; Function to return lcm of two numbers ; Make a graph ; Add edge ; Count reachable nodes from every node . ; Driver code
import math NEW_LINE def lcm ( a , b ) : NEW_LINE INDENT return ( a * b ) // ( math . gcd ( a , b ) ) NEW_LINE DEDENT def dfs ( src , adj , visited ) : NEW_LINE INDENT visited [ src ] = True NEW_LINE count = 1 NEW_LINE if adj [ src ] != 0 : NEW_LINE INDENT for i in range ( len ( adj [ src ] ) ) : NEW_LINE INDENT if ( not visited [ adj [ src ] [ i ] ] ) : NEW_LINE INDENT count += dfs ( adj [ src ] [ i ] , adj , visited ) NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def findMinTime ( arr , P , n ) : NEW_LINE INDENT adj = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if adj [ arr [ i ] ] == 0 : NEW_LINE INDENT adj [ arr [ i ] ] = [ ] NEW_LINE DEDENT adj [ arr [ i ] ] . append ( P [ i ] ) NEW_LINE DEDENT visited = [ 0 ] * ( n + 1 ) NEW_LINE ans = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT ans = lcm ( ans , dfs ( i , adj , visited ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE P = [ 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMinTime ( arr , P , n ) ) NEW_LINE