Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move all zeroes to the end of an array with the order of the elements preserved

Can anyone tell me what have I done wrong in this code ?

In this approach, I traverse the array and, as soon as I find a 0 element, I traverse to the right of the 0, and swap it with the 1st non-0 element found.

class Solution {
    public void moveZeroes(int[] nums) {
       for (int i = 0; i < nums.length;i++) {
           if (nums[i]==0) {
               for(int j = i+1; j < nums.length;j++) {
                   if(nums[j]!=0) {
                       int temp = nums[i];
                       nums[i]=nums[j];
                       nums[j]=temp;
                   }
               }
           }
       } 
       
    }
}

For this following input,
[0,1,0,3,12]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The expected output is
[1,3,12,0,0]

But I am getting
[12,3,1,0,0]

>Solution :

Assuming there is no requirement with regard to the ordering, just to keep the original sequence with shifted zeros only you forgot to break the cycle once you have done a shift, so the corresponding method should look like the following:

class Solution {
    public void moveZeroes(int[] nums) {
       for (int i = 0; i < nums.length;i++) {
           if (nums[i]==0) {
               for(int j = i+1; j < nums.length;j++) {
                   if(nums[j]!=0) {
                       int temp = nums[i];
                       nums[i]=nums[j];
                       nums[j]=temp;
                       break;
                   }
               }
           }
       } 
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading