Skip to content

Instantly share code, notes, and snippets.

@ritik-agrawal
Created August 6, 2023 08:38
Show Gist options
  • Save ritik-agrawal/48fc4fab73e602da680ae22aa5b52628 to your computer and use it in GitHub Desktop.
Save ritik-agrawal/48fc4fab73e602da680ae22aa5b52628 to your computer and use it in GitHub Desktop.
Leet Code: Move the zeros to the last of the given int[] while maintaining the relative order of the non zero numbers.
class Solution {
public void moveZeroes(int[] nums) {
var len = nums.length;
var mark = 0;
for (int i = 0; i < len; i++){
if (nums[i] != 0){
nums[mark] = nums[i];
mark++;
}
}
for (int j = mark; j < len; j++){
nums[j] = 0;
}
}
}
@ritik-agrawal
Copy link
Author

Observation

The above problem was solved using two approaches by me and the most optimal solution was found online.

Approach 1

  • get the next zero location
  • get the next non-zero location
  • swap them.
  • repeat till the next non-zero location is equal to the length of the array given.

This approach beats 12% of the total solutions submitted with a runtime of 30 ms.

Approach 2

  • iterate through the array
  • if the current value is non zero updates the marker by one else don't update
  • if the current value is non-zero and the iterator and marker are not the same then swap nums.

The above approach beats 42% of the total solutions submitted with a runtime of 2 ms.

Approach 3

  • iterate through the array
  • if the current value is non-zero then update the marker location with the value and update the marker.
  • after iteration is complete. iterate from the marker position to the last making the values as 0.

The above approach beats 100% of the cases with a runtime of 1 ms.

A link to all the submissions. Click here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment