Member-only story

Leetcode: Move Zeros

Akiko Green
Nerd For Tech
Published in
3 min readMar 8, 2021
The Simpsons — Giphy

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:

  1. you must do this in-place without making a copy of the array
  2. 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.

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Akiko Green
Akiko Green

Written by Akiko Green

Software Engineer, Novice Blogger, Indoor Climber and Dog sitting expert 🥰

No responses yet