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
Top comments (0)