top of page

Looking to master object-oriented and system design for tech interviews or career growth?

  • Improve your system design and machine coding skills.

  • Study with our helpful resources.

  • Prepare for technical interviews and advance your career.

**We're in beta mode and would love to hear your feedback.

Rearrange Array InterviewBit Solution

Sep 5, 2020
1 min read

Updated: Sep 8, 2020


Problem Description:

Rearrange a given array so that Arr[i] becomes Arr[Arr[i]] with O(1) extra space.


Example:

Input : [1, 0] 
Return : [0, 1] 

Lets say N = size of the array. Then, following holds true :

  • All elements in the array are in the range [0, N-1]

  • N * N does not overflow for a signed integer

Solution:

void Solution::arrange(vector<int> &A) {
    int n=A.size();
    for(int i=0;i<A.size();i++){
        A[i]=A[i]*n;
    }
    for(int i=0;i<A.size();i++){
        A[i]=A[i]+A[A[i]/n]/n;
    }
    for(int i=0;i<A.size();i++){
        A[i]= A[i]%n;
    }
}

1 Comment


The part where the old and new values are packed into the same integer is what made this click for me—I’d never thought of using the modulo step to peel them apart. It’s a bit like how I track my casino payments at https://kasinomaksut.com: the original balance and the pending transaction sit in one place until the final amount is settled.

Like
bottom of page