Minimum time to return array to its original state after given modifications | Java 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 java . util . * ; class GFG { static int lcm ( int a , int b ) { return ( a * b ) / ( __gcd ( a , b ) ) ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static int dfs ( int src , Vector < Integer > adj [ ] , boolean [ ] visited ) { visited [ src ] = true ; int count = 1 ; for ( int i = 0 ; i < adj [ src ] . size ( ) ; i ++ ) if ( ! visited [ adj [ src ] . get ( i ) ] ) count += dfs ( adj [ src ] . get ( i ) , adj , visited ) ; return count ; } static int findMinTime ( int arr [ ] , int P [ ] , int n ) { Vector < Integer > [ ] adj = new Vector [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { adj [ arr [ i ] ] . add ( P [ i ] ) ; } boolean [ ] visited = new boolean [ n + 1 ] ; int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! visited [ i ] ) { ans = lcm ( ans , dfs ( i , adj , visited ) ) ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 } ; int P [ ] = { 3 , 2 , 1 } ; int n = arr . length ; System . out . print ( findMinTime ( arr , P , n ) ) ; } }