My Thinking and Approach
Introduction
In this problem, I was given an array of integers and asked to move all zeroes to the end of the array.
The important condition is that the relative order of non-zero elements should be maintained.
Problem Statement
Given an array of integers
numsMove all 0’s to the end
-
Conditions:
- Maintain relative order of non-zero elements
- Perform operation in-place
- Do not use extra space
My Initial Thought
At first, I considered:
- Creating a new array
- Adding all non-zero elements
- Then adding zeroes at the end
But this approach uses extra space.
Key Observation
Instead of using extra space:
- I can shift all non-zero elements to the front
- Then fill the remaining positions with zeroes
Optimized Approach
I decided to use a pointer to track position of non-zero elements.
Logic:
- Traverse the array
- Place non-zero elements at correct position
- Fill remaining positions with zeroes
My Approach (Step-by-Step)
- Initialize a pointer
pos = 0 - Traverse the array:
-
If element is not zero
→ place it at indexpos
→ incrementpos- After traversal:
Fill remaining elements with 0
Code (Python)
Below is the implementation clearly separated inside a code block:
class Solution:
def moveZeroes(self, nums):
pos = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[pos] = nums[i]
pos += 1
for i in range(pos, len(nums)):
nums[i] = 0
Example Walkthrough
Input:
nums = [0, 1, 0, 3, 12]
Steps:
- Move non-zero elements → [1, 3, 12, _, _]
- Fill remaining with zeroes → [1, 3, 12, 0, 0]
Output:
[1, 3, 12, 0, 0]
Complexity Analysis
| Type | Complexity |
|---|---|
| Time Complexity | O(n) |
| Space Complexity | O(1) |
Key Takeaways
- In-place modification is important
- Two-pass solution is efficient
- Maintaining order is key
Conclusion
This problem helped me understand how to rearrange elements efficiently while maintaining order and without using extra space.
Top comments (0)