Move Zeros
Problem Statement
Given an array of integers, move all zeros to the end of the array while maintaining the relative order of non zero elements.
Examples
Input
arr = [0, 1, 0, 3, 12]
Output
[1, 3, 12, 0, 0]
Input
arr = [0, 0, 1]
Output
[1, 0, 0]
Approach 1 Using Extra Space
Create a new array to store non zero elements first and then append zeros.
Steps
1 Traverse the array and store non zero elements
2 Count number of zeros
3 Append zeros at the end
Code
```python id="mz1"
def moveZeros(arr):
result = []
zero_count = 0
for num in arr:
if num != 0:
result.append(num)
else:
zero_count += 1
for _ in range(zero_count):
result.append(0)
return result
---
## Approach 2 In Place Method
Rearrange elements within the same array.
---
### Steps
1 Initialize index for non zero elements
2 Traverse the array
3 If element is non zero swap it with current index
4 Increment index
---
### Code
```python id="mz2"
def moveZeros(arr):
j = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[i], arr[j] = arr[j], arr[i]
j += 1
return arr
Explanation
The idea is to push all non zero elements to the front while shifting zeros to the end. The order of non zero elements remains unchanged.
Expected Output
Input
arr = [0, 1, 0, 3, 12]
Output
[1, 3, 12, 0, 0]
Conclusion
Moving zeros to the end is a common problem that helps in understanding array manipulation and in place operations. It is frequently asked in coding interviews.
Practice this problem with different inputs to improve your coding skills.
Top comments (0)