An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
March 26, 2022 05:38 pm GMT
Original Link: https://dev.to/vnaydev/move-zeroes-3o00
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 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
Original Link: https://dev.to/vnaydev/move-zeroes-3o00
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To