this is my submission on leetcode
Help me out in this problem
Checking your code, be patient 
I am trying to debug it, till then if you can elaborate your approach it would be time saving .
Mistake 1 : 1<=ar[i]<n line number 8
Secondly in the test case [1,2,0] let me tell you what is happening
-
when your i is at 0
your ar[i] has a value of 1 , so it won’t go in if statement of line 8 -
when your i is at 1
your ar[i] has a value of 2 , so it will go in if statement of line 8. After doing operation in your if statement. Your array is [2,1,0] -
when your i is at 2
your ar[i] has a value of 0 , so it won’t go in if statement of line 8.
Final array [2,1,0] goes in second for loop
goes in first if statement returns 1, but the actual answer is 3.
I would suggest you to first try this question using map and then try this it’s same as of your code
this approach is what you wanted to do, so you can check from here where were you actually wrong 
not only just while loop it’s also the if condition that you forgot
why while loop is being used for tc
3 4 -1 1 where the output is 2, 1 is swapped by 4 [3,-1,1,4]
now 1 is at position 2 which is not at it’s right place so we swap again with -1 now 1 is at 0 and -1 is at 1 [-1,3,1,4]
So there would be more such test cases which not just only need swapping one time but multiple times.
Your final array would look like [-1,3,1,4]
It remains O(N) only, after using while loop too.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.