Member-only story
Leetcode: Move Zeros
Published in
3 min readMar 8, 2021
Move Zeroes is a leetcode challenge that prompts you to move all the zeroes in an array to the end of that array.
The Problem:
Given an array of nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
- you must do this in-place without making a copy of the array
- Minimize the total number of operations.
Now, there are many ways of doing this algorithm, I will be displaying two different ways to approach this very challenge!
The First Approach
The Pseudocode:
we can create a pointer called j, and assign j to 0iterate through the array with a for loop
now -->
if the number we encounter is not a 0
then we take j and assign that value to that non zero number, increment j to the next index up.once that loop is complete
loop through the array again
this time i is assigned to j during the lop
assign i to 0 <== essentially what this is doing is filling the rest of the array with the necessary zeroes at the end.