Minimum time to return array to its original state after given modifications | Function to return lcm of two numbers ; Make a graph ; Add edge ; Count reachable nodes from every node . ; Driver code
function lcm ( a , b ) { return ( a * b ) / ( __gcd ( a , b ) ) ; } function __gcd ( a , b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } function dfs ( src , adj , visited ) { visited [ src ] = true ; let count = 1 ; for ( let i = 0 ; i < adj [ src ] . length ; i ++ ) if ( ! visited [ adj [ src ] [ i ] ] ) count += dfs ( adj [ src ] [ i ] , adj , visited ) ; return count ; } function findMinTime ( arr , P , n ) { let adj = new Array ( n + 1 ) ; for ( let i = 0 ; i < n + 1 ; i ++ ) adj [ i ] = new Array ( ) ; for ( let i = 0 ; i < n ; i ++ ) { adj [ arr [ i ] ] . push ( P [ i ] ) ; } let visited = new Array ( n + 1 ) ; let ans = 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( ! visited [ i ] ) { ans = lcm ( ans , dfs ( i , adj , visited ) ) ; } } return ans ; } let arr = [ 1 , 2 , 3 ] ; let P = [ 3 , 2 , 1 ] ; let n = arr . length ; document . write ( findMinTime ( arr , P , n ) ) ;