Rearrange an array with O(1) extra space

PHOTO EMBED

Mon Jun 19 2023 06:59:26 GMT+0000 (Coordinated Universal Time)

Saved by @DxBros #c++ #cyclic_rotation #rearrangement #array #o(1)_space

class Solution{
    public:
    // arr: input array
    // n: size of array
    //Function to rearrange an array so that arr[i] becomes arr[arr[i]]
    //with O(1) extra space.
    void arrange(long long v[], int n) {
        // Your code here
        for(int i= 0; i < n; i++){
            if(v[i] >= 0){
                int val = -v[i], ini = i, p = i;
                while( v[p] != ini){
                    int t = v[p];
                    v[p] = v[t];
        		    if(v[p] == 0)
        			    v[p] = INT_MIN;
        		    else
        			    v[p] *= -1;
            		p = t;
                }
                v[p] = val;
            }
        }
        for(int i= 0; i <n ;i++)
            if(v[i] != INT_MIN)
                v[i] *= -1;
            else
                v[i] = 0;
    }
};
content_copyCOPY

https://practice.geeksforgeeks.org/problems/rearrange-an-array-with-o1-extra-space3142/1