- Arrays, Mathematical

Count of pass required to visit same index again by moving arr[i] to index arr[i]

Given an array(1-based indexing) arr[] of permutation of the first N natural numbers, the task for each element is to find the number of moves required to reach that index such that in each move, array element at index i moves to the array element at index arr[i].Examples:Input: arr[] = {2, 3, 1}Output: 3 3 3  Explanation:For array element arr[1] = 2, the set of moves of indices are 1 -> 2 -> 3 -> 1. The total count of moves required is 3.For array element arr[2] = 3, the set of moves of indices are 2 -> 3 -> 1 -> 2. The total count of moves required is 3.For array element arr[3] = 1, the set of moves of indices are 3 -> 1 -> 2 -> 3. The total count of moves required is 3.Input: arr[] = {4, 6, 2, 1, 5, 3}Output: 2 3 3 2 1 3Approach: The given problem can be solved by finding the number of moves required for every array element for each index. Follow the steps below to solve the given problem:Traverse the given array arr[] using the variable i and perform the following steps:Initialize a variable, say count that stores the total number of moves required.Initialize a variable, say K as i and iterate a do-while loop and in that loop update the value of K to arr[K] and increment the value of count by 1 until K is not the same as the value of i.After completing the above steps, print the value of count as the resultant count of move required for the current index.Below is the implementation of the above approach:C++#include using namespace std;  void numberOfPasses(vector arr, int N){        for (int i = 0; i < N; ++i) {        --arr[i];    }      for (int i = 0; i < N; ++i) {                  int cnt = 0;                  int k = i;          do {                          ++cnt;                          k = arr[k];          } while (k != i);                  cout