I have any array with value 0,0,0,0,0,0,0,0,1,1,1
Now my required output should be like each zero will be in odd index and 1 will be in even and if 0 left after that it should be copied after 1 and viceversa.
Means the output will be 0,1,0,1,0,1,0,0,0,0,0….
But the above operation must be done in a single pass of array
- So I created an array with same size ,
- then I started traversing the main array and one’s 0 is encoutered I put a counter to set the value in odd index and viceversa
- In the end when the index crossed the length of new array created , I started adding the 0 into the new cell in even mode from backward.
What can be the other better solution.
You don’t need an extra array for this. You can do it in-place. Just keep two pointers, one which stops after every odd step and one which finds the
1s. When the second pointer encounters a1just swap it with the first pointer, increment the first pointer. Do this for the length of the array.