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.
- Initialize a variable (say count) equal to 0.
- Start a for loop from 0 to array.length
- If we come across a non-zero element,
- Insert the current element to index = count of the array.
- Increment count.
- Start the second loop from count to array.length
- In the body, keep inserting 0 to each current location as it iterates.
- Return array
Optimized solution :
- Initialize a variable (say count) equal to 0.
- Start a for loop from 0 to array.length
- If we come across a non-zero element,
- Swap the current element with the element at index = count of the array.
- Increment count.
- Return array
This content originally appeared on DEV Community and was authored by Vinay Krishnan
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.
APA
MLA
Vinay Krishnan | Sciencx (2022-03-26T17:38:47+00:00) Move zeroes. Retrieved from https://www.scien.cx/2022/03/26/move-zeroes/
" » Move zeroes." Vinay Krishnan | Sciencx - Saturday March 26, 2022, https://www.scien.cx/2022/03/26/move-zeroes/
HARVARDVinay Krishnan | Sciencx Saturday March 26, 2022 » Move zeroes., viewed ,<https://www.scien.cx/2022/03/26/move-zeroes/>
VANCOUVERVinay 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.