Move zeroes

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

Brute force solution:

We can solve this question using two for loops.

Initialize a variable (say count) equal to 0.
Start a for loop from 0 to array.length
If we come across a non-zero e…


This content originally appeared on DEV Community and was authored by Vinay Krishnan

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


This content originally appeared on DEV Community and was authored by Vinay Krishnan


Print Share Comment Cite Upload Translate Updates
APA

Vinay Krishnan | Sciencx (2022-03-26T17:38:47+00:00) Move zeroes. Retrieved from https://www.scien.cx/2022/03/26/move-zeroes/

MLA
" » Move zeroes." Vinay Krishnan | Sciencx - Saturday March 26, 2022, https://www.scien.cx/2022/03/26/move-zeroes/
HARVARD
Vinay Krishnan | Sciencx Saturday March 26, 2022 » Move zeroes., viewed ,<https://www.scien.cx/2022/03/26/move-zeroes/>
VANCOUVER
Vinay Krishnan | Sciencx - » Move zeroes. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/26/move-zeroes/
CHICAGO
" » Move zeroes." Vinay Krishnan | Sciencx - Accessed . https://www.scien.cx/2022/03/26/move-zeroes/
IEEE
" » Move zeroes." Vinay Krishnan | Sciencx [Online]. Available: https://www.scien.cx/2022/03/26/move-zeroes/. [Accessed: ]
rf:citation
» Move zeroes | Vinay Krishnan | Sciencx | https://www.scien.cx/2022/03/26/move-zeroes/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.