Mark As Completed Discussion

One Pager Cheat Sheet

  • Write a function zerosToEnd which moves all zeros in an array to its end, while maintaining the order of all other elements, within O(n) time and O(1) space complexity constraints.
  • Run through examples and separate the [1, 2, 4] from the [0, 0, 0] to achieve [1, 2, 4, 0, 0, 0].
  • We need to separate the 0s and non-0s, find out where the non-0s need to be index-wise, and keep track of the number of 0s in order to solve this problem using a potential brute force solution.
  • We can do better by changing the position of elements in the array in-place, which requires us to mutate and keep track of indexes.
  • Try simplifying the problem by only keeping track of one index, or use multiple trackers to know about multiple positions at once.
  • Multiple pointers are key for efficiently moving all zeros to the end of an array in O(n) time complexity and constant space complexity.

This is our final solution.

To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Got more time? Let's keep going.

If you had any problems with this tutorial, check out the main forum thread here.