educative.io

Educative

Leetcode and alternative solutions

To practice on Leetcode
It has more number of tests in there so I suggest you to have a go:
move-zeros
Note the problem moves the zeros in the other directions.

Two solutions:

1. Storing the position of zero index.

class moveZerosToLeft{
  static void move_zeros_to_left_in_array(int[] arr) {
     int zeroIdx = -1;
     for (int i = arr.length - 1; i >= 0; i--) {
         if (arr[i] == 0 && zeroIdx == -1) {
             zeroIdx = i;
         } else if (arr[i] != 0 && zeroIdx != -1){
             arr[zeroIdx] = arr[i];
             arr[i] = 0;
             zeroIdx--;
         } 
     }    
  }
}  

Method 2. storing the position of non-zero index.
This solution is from the leetcode, I think it is very elegant.
This has the same logic as the provided solution but implemented more nicely.

class moveZerosToLeft{
  static void move_zeros_to_left_in_array(int[] arr) {
for (int nonZeroIdx = arr.length-1, i = arr.length-1; i >=0; i--) {
  if (arr[i] != 0) {
    if (nonZeroIdx != i) {
      int temp = arr[i];
      arr[i] = arr[nonZeroIdx];
      arr[nonZeroIdx] = temp;
    }
    nonZeroIdx--;
  }
}
  }
}

Quick test shows both methods do same number of operations for a given input.
But method 2 is easier to read.

Hi @Wonjoon_Seol,

Umer here from the Educative content team. Thanks for sharing these alternate solutions through our platform.
We appreciate your interest!

Happy learning