Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 26, 2022 05:38 pm GMT

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

Original Link: https://dev.to/vnaydev/move-zeroes-3o00

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To