Steps to return to {1, 2, ..n} with specified movements

Given an array moves[] that contains a permutation of first n natural numbers, each element of this array represents a movement that is each element shows an index where the element goes after each step. Now following these steps we need to tell after how many steps array [1..n] returns back to [1..N]. A step is defined as follows, after one step each element will be moved to position defined by moves array indices.

Examples :

Input  : moves[] = [4, 5, 1, 3, 2]
Output : 6
Explanation:
We need to consider an array of first 5 
natural numbers, i.e., arr[] = {1, 2, 3, 4, 5} as
size of moves[] is 5.
Now we one by one move elements of arr[] using 
given moves.
      moves[] = [4, 5, 1, 3, 2]
    arr[] = [1, 2, 3, 4, 5] 
In step 1, we move 1 to position 4, 2 to position
5, 3 to position 1, 4 to position 3 and 5 to 
position 2.
After step 1: arr[] = [3, 5, 4, 1, 2]
In step 2, we move 3 to position 4, 5 to position
5, 4 to position 1, 1 to position 3 and 2 to 
position 2
After step 2: arr[] = [4, 2, 1, 3, 5]
After step 3: arr[] = [1, 5, 3, 4, 2]
After step 4: arr[] = [3, 2, 4, 1, 5]
After step 5: arr[] = [4, 5, 1, 3, 2]
After step 6: arr[] = [1, 2, 3, 4, 5]
So we can reach to initial array in 6 steps, 
this is the minimum steps for reverting to 
the initial configuration of array.

Input  : moves[] = {3, 2, 1}
Output : 2



We can solve this problem by observing a pattern among the sequences which are formed. A particular set of element of moves array, forms a cycle. As in above moves array example [4, 1, 3] and [5, 2] are two such sets. These two cycles are independent.

[4, 1, 3] causes [1, 3, 4] -> [3, 4, 1] -> [4, 1, 3] 
-> [1, 3, 4] -> [3, 4, 1] -> [4, 1, 3] -> [1, 3, 4]

[5, 2] causes [2, 5] -> [5, 2] -> [2, 5] -> [5, 2]
 -> [2, 5] -> [5, 2] -> [2, 5]

We can see from above changes that a cycle of length 3, takes 3 steps to reach to same state and cycle of length 2, takes 2 steps to reach to same state. In general if a cycle has length N then after N steps we can reach to same state.
Now if given moves array has just one cycle, then we can reach to starting state in number of moves equal to total elements in array but if it has more than 1 cycle then all of them move their elements independently and all of them will reach to starting state after x number of moves where x should be divisible by all cycle lengths, as smallest x which divides all cycle length is their LCM, we remain with finding LCM of all cycle lengths.
Cycle lengths can be found by visiting elements one by one, starting from any element we will move until we reach to starting element and we will count number of elements in this process which will be the corresponding cycle length.

Below is example of cycles found for some moves arrays,
[2, 3, 1, 5, 4]     ->  [2, 3, 1] and [5, 4]
[1, 2, 3, 4, 5] ->  [1] [2] [3] [4] [5]
[2, 3, 4, 1, 5] ->  [2, 3, 4, 1] and [5]

Only thing remain is to calculate LCM of these lengths which can be calculated easily using GCD.

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to get minimum steps to return to
// initial array with specified movement
#include <bits/stdc++.h>
using namespace std;
  
// Utility method to get lcm of a and b
int lcm(int a, int b)
{
    return (a * b) / __gcd(a, b);
}
  
// Method returns minimum number of steps to
// return to initial array
int getMinStepsToSort(int moves[], int N)
{
    // initially all cells are unvisited
    bool visit[N];
    memset(visit, false, sizeof(visit));
  
    // looping over all elements to get
    // various cycle
    int steps = 1;
    for (int i = 0; i < N; i++) {
        // if already visited, that means it
        // was a part of some cycle
        if (visit[i])
            continue;
  
        int cycleLen = 0;
  
        // Looping among cycle elements,  -1 is
        // for coverting value to 0-index based
        for (int j = i; !visit[j]; j = moves[j] - 1) {
            cycleLen++;
            visit[j] = true;
        }
  
        // Take the lcm of current result and
        // new cycle length
        steps = lcm(steps, cycleLen);
    }
    return steps;
}
  
// Driver code to test above methods
int main()
{
    int moves[] = { 4, 5, 1, 3, 2 };
    int N = sizeof(moves) / sizeof(int);
  
    cout << getMinStepsToSort(moves, N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to get minimum steps to
// return to initial array with specified
// movement
import java.util.Arrays;
  
class GFG {
  
    // Recursive function to return gcd
    // of a and b
    static int __gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0 || b == 0)
            return 0;
  
        // base case
        if (a == b)
            return a;
  
        // a is greater
        if (a > b)
            return __gcd(a - b, b);
  
        return __gcd(a, b - a);
    }
  
    // Utility method to get lcm of a and b
    static int lcm(int a, int b)
    {
        return (a * b) / __gcd(a, b);
    }
  
    // Method returns minimum number of steps
    // to return to initial array
    static int getMinStepsToSort(int moves[],
                                 int N)
    {
  
        // initially all cells are unvisited
        boolean visit[] = new boolean[N];
        Arrays.fill(visit, false);
  
        // looping over all elements to get
        // various cycle
        int steps = 1;
        for (int i = 0; i < N; i++) {
  
            // if already visited, that
            // means it was a part of some
            // cycle
            if (visit[i])
                continue;
  
            int cycleLen = 0;
  
            // Looping among cycle elements,
            // -1 is for coverting value to
            // 0-index based
            for (int j = i; !visit[j];
                 j = moves[j] - 1) {
  
                cycleLen++;
                visit[j] = true;
            }
  
            // Take the lcm of current result
            // and new cycle length
            steps = lcm(steps, cycleLen);
        }
  
        return steps;
    }
  
    // Driver code
    public static void main(String arg[])
    {
        int moves[] = { 4, 5, 1, 3, 2 };
        int N = moves.length;
  
        System.out.print(getMinStepsToSort(
            moves, N));
    }
}
  
// This code is contributed by Anant Agarwal.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to get
# minimum steps to return to
# initial array with
# specified movement
  
# Recursive function to
# return gcd of a and b
def  __gcd(a, b):
  
    # Everything divides 0 
    if (a == 0 or b == 0):
        return 0
        
    # base case
    if (a == b):
        return a
        
    # a is greater
    if (a > b):
        return __gcd(a-b, b)
    return __gcd(a, b-a)
  
# Utility method to
# get lcm of a and b
def lcm(a, b):
  
    return (a * b) // __gcd(a, b)
  
   
# Method returns minimum
# number of steps to
# return to initial array
def getMinStepsToSort(moves, N):
  
    # initially all cells are unvisited
    visit =[False for i in range(N + 1)]
   
    # looping over all
    # elements to get
    # various cycle
    steps = 1
    for i in range(N):
      
        # if already visited,
        # that means it
        # was a part of some cycle
        if(visit[i]):
            continue
   
        cycleLen = 0
   
        # Looping among cycle
        # elements,  -1 is
        # for coverting value
        # to 0-index based
        j = i
        while(not visit[j]):
          
            cycleLen+= 1
            visit[j] = True
            j = moves[j] - 1
      
        # Take the lcm of
        # current result and 
        # new cycle length
        steps = lcm(steps, cycleLen)
  
    return steps
  
# Driver code
  
moves = [4, 5, 1, 3, 2]
N = len(moves)
   
print(getMinStepsToSort(moves, N))
  
# This code is contributed
# by Anant Agarwal.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to get minimum steps to return 
// to initial array with specified movement
using System;
  
class GFG {
  
    // Recursive function to return gcd
    // of a and b
    static int __gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0 || b == 0)
            return 0;
  
        // base case
        if (a == b)
            return a;
  
        // a is greater
        if (a > b)
            return __gcd(a - b, b);
  
        return __gcd(a, b - a);
    }
  
    // Utility method to get lcm of a and b
    static int lcm(int a, int b)
    {
        return (a * b) / __gcd(a, b);
    }
  
    // Method returns minimum number of steps
    // to return to initial array
    static int getMinStepsToSort(int[] moves,
                                       int N)
    {
        // initially all cells are unvisited
        bool[] visit = new bool[N];
  
        // looping over all elements to get
        // various cycle
        int steps = 1;
        for (int i = 0; i < N; i++) {
  
            // if already visited, that
            // means it was a part of some cycle
            if (visit[i])
                continue;
  
            int cycleLen = 0;
  
            // Looping among cycle elements,
            // -1 is for coverting value to
            // 0-index based
            for (int j = i; !visit[j];
                j = moves[j] - 1) {
  
                cycleLen++;
                visit[j] = true;
            }
  
            // Take the lcm of current result
            // and new cycle length
            steps = lcm(steps, cycleLen);
        }
  
        return steps;
    }
  
    // Driver code
    public static void Main()
    {
        int[] moves = { 4, 5, 1, 3, 2 };
        int N = moves.Length;
  
        Console.WriteLine(getMinStepsToSort(moves, N));
    }
}
  
// This code is contributed by vt_m.

chevron_right



Output:

6

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : vt_m



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.