31. Move all zeroes to the end of the array
The problem can be found at the following link: Question Link
My Approach
To move all zeroes to the end of the array, I use a two-pointer approach.
I maintain two pointers,
i
andj
.Pointer
i
is used to iterate through the array and move non-zero elements to the front of the array.Pointer
j
keeps track of the position where we should place the next non-zero element.Once we have moved all non-zero elements to the front, I fill the remaining positions with zeroes.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)
, wheren
is the number of elements in the array.Auxiliary Space Complexity:
O(1)
, as we are not using any extra data structures.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated