DEV Community

Vinay Krishnan
Vinay Krishnan

Posted on

Move zeroes

Leetcode problem : https://leetcode.com/problems/move-zeroes/

Brute force solution:

We can solve this question using two for loops.

  1. Initialize a variable (say count) equal to 0.
  2. Start a for loop from 0 to array.length
  3. If we come across a non-zero element,
    • Insert the current element to index = count of the array.
    • Increment count.
  4. Start the second loop from count to array.length
  5. In the body, keep inserting 0 to each current location as it iterates.
  6. Return array

Optimized solution :

  1. Initialize a variable (say count) equal to 0.
  2. Start a for loop from 0 to array.length
  3. If we come across a non-zero element,
    • Swap the current element with the element at index = count of the array.
    • Increment count.
  4. Return array

Latest comments (0)