Snippets Collections
class Solution{

    //Function to rearrange  the array elements alternately.
    public static void rearrange(long arr[], int n)
    {
        //Initialising index of first minimum and first maximum element. 
    	int max_idx = n - 1, min_idx = 0; 
    
    	 //Storing maximum element of array.
    	long max_elem = arr[n - 1] + 1; 
    
    	for (int i = 0; i < n; i++) { 
    	    
    		//At even index, we have to put maximum elements in decreasing order. 
    		if (i % 2 == 0) { 
    			arr[i] += (arr[max_idx] % max_elem) * max_elem; 
    			//Updating maximum index.
    			max_idx--; 
    		} 
    
    		//At odd index, we have to put minimum elements in increasing order. 
    		else { 
    			arr[i] += (arr[min_idx] % max_elem) * max_elem; 
    			//Updating minimum index.
    			min_idx++; 
    		} 
    	} 
    
    	//Dividing array elements by maximum element to get the result. 
    	for (int i = 0; i < n; i++) 
    		arr[i] = arr[i] / max_elem;
        
    }
    
}
class Solution
{
    //Function to rearrange an array so that arr[i] becomes arr[arr[i]]
    //with O(1) extra space. 
    static void arrange(long arr[], int n)
    {
        int i = 0;
        
        //Increasing all values by (arr[arr[i]]%n)*n to store the new element.
        for(i = 0; i < n; i++)
         arr[(int)i]+=(arr[(int)arr[(int)i]]%n)*n;
        
        //Since we had multiplied each element with n.
        //We will divide by n too to get the new element at that 
        //position after rearranging.
        for(i = 0; i < n; i++)
            arr[(int)i] = arr[(int)i]/n;
    }
}
star

Tue Feb 08 2022 05:22:26 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/-rearrange-array-alternately-1587115620/1/?track=DSASP-Arrays&batchId=190

#java #gfg #geeksforgeeks #arrays #practice #rearrange #alternately
star

Tue Feb 08 2022 05:08:33 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/rearrange-an-array-with-o1-extra-space3142/1/?track=DSASP-Arrays&batchId=190

#java #gfg #geeksforgeeks #arrays #practice #rearrange

Save snippets that work with our extensions

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