lundi 8 juillet 2019

[InterviewBit]Rearrange Array- Why my solution is accepted?

Problem Link- https://www.interviewbit.com/problems/rearrange-array/

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

Example:

Input : [1, 0]

Return : [0, 1]

My solution-

void findAns(vector<int> &A, int idx){
    if(idx >= A.size()) return;
    int cur = A[A[idx]];
    findAns(A, idx+1);
    A[idx] = cur;
}

void Solution::arrange(vector<int> &A) {
    findAns(A, 0);
}

Doubt- The problem clearly states that we have to use O(1) extra space. In my algorithm I am storing a number at every step of recursion. So, at the end of recursion whole of array gets stored in recursion stack. I think it is taking O(n) space. So, why my solution is accepted?

Aucun commentaire:

Enregistrer un commentaire