Given a permutation array P (1-based indexing), find the total number of steps required to sort the same array using the permutation array.

Constraints: n = arr.length 2<=n<=10^5

Example: Say P =[2,5,4,3,1]

Copy the array from P to arr arr = [2,5,4,3,1] step1 -> arr = [5,1,3,4,2] {Here the elements are arranged according to the permutation array, (i.e, permutation array P is considered here as index array to arrange elements) Here, 2nd element (5) comes 1st place because in P, 2 is at 1st position 5th element (1) comes 2nd place because in P, 5 is at 2nd position and so on...}

step2 -> arr = [1,2,4,3,5] step3 -> arr = [2,5,4,3,1] step4 -> arr = [5,1,4,3,2] step5 -> arr = [1,2,3,4,5]

Hence, the total number of steps required = 5

ex2 [3, 1, 2, 5, 4] ans is 5

ex 3 [3 4 2 1] ans is 3

I solve in O(N*N) getting tle

int n;
cin >> n;
vector v(n);
map<pair<int, int>, int> mp;
int cnt1 = 0, cnt2 = 0;
fo(i, 0, n)
{
cin >> v[i];
}

vector<int> v1 = v;
sort(v1.begin(), v1.end());
int ans = 0;
vector<int> v2 = v;
while (1)
{
    if (v2 == v1)
        break;
    vector<int> v3(n);
    for (int i = 0; i < n; i++)
    {
        v3[i] = v2[v[i] - 1];
    }
    v2 = v3;
    ans++;
}
cout << ans+1 << endl;

Can anyone solve this question in less then O(N*N) ?
Comments (7)