Day 2 - Move All Zeroes to End
π Day 2. Move All Zeroes to End π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
Given an array arr[], move all the zeros in the array to the end while maintaining the relative order of non-zero elements. The modification should be done in-place.
π Example Walkthrough:
Input:
arr[] = [1, 2, 0, 4, 3, 0, 5, 0]Output:
[1, 2, 4, 3, 5, 0, 0, 0]Explanation: The three zeros are moved to the end while the relative order of non-zero elements is maintained.
Input:
arr[] = [10, 20, 30]Output:
[10, 20, 30]Explanation: No change in the array as there are no zeros.
Input:
Output:
Explanation: No change in the array as all elements are zeros.
π― My Approach:
Two-Pointer Technique:
Use a pointer
nonZeroIndexto track the position where the next non-zero element should be placed.Traverse the array, and whenever a non-zero element is encountered, swap it with the element at the
nonZeroIndexand increment the pointer.This ensures all non-zero elements are shifted to the front, and zeros naturally move to the end.
Edge Cases:
If the array contains no zeros, return the array as is.
If the array contains only zeros, no changes are needed.
π Time and Auxiliary Space Complexityπ
Expected Time Complexity: O(n), where
nis the number of elements in the array. Each element is traversed once to determine its position.Expected Auxiliary Space Complexity: O(1), as no additional space is used apart from a few variables.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated