Snippets Collections
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;
    }
};
star

Mon Jun 19 2023 06:59:26 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/rearrange-an-array-with-o1-extra-space3142/1

#c++ #cyclic_rotation #rearrangement #array #o(1)_space

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension