Leetcode Problem
Leetcode Problem
Problem Statement
Given an integer array nums, move all 0s to the end of it while maintaining the relative order of
the non-zero elements.
Example
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Constraints
● Do not return anything; modify nums in-place instead.
● Minimize the total number of operations.
Approach
To solve this problem efficiently, we can use a two-pointer technique to rearrange the array
in-place. The idea is to maintain a pointer (last_non_zero_found_at) that keeps track of the
position where the next non-zero element should be placed.
As we iterate through the array, we swap non-zero elements with the element at the
last_non_zero_found_at index and then increment this pointer.
Algorithm
This approach ensures that all non-zero elements are moved to the beginning of the array in
their original order, and all zeros are moved to the end.
Python Implementation
def move_zeroes(nums):
last_non_zero_found_at = 0
for current in range(len(nums)):
if nums[current] != 0:
nums[last_non_zero_found_at], nums[current] = nums[current],
nums[last_non_zero_found_at]
last_non_zero_found_at += 1
Explanation
● last_non_zero_found_at keeps track of the index where the next non-zero element
should be placed.
● The loop iterates over each element in the array.
● When a non-zero element is found, it is swapped with the element at the
last_non_zero_found_at index.
● After the swap, last_non_zero_found_at is incremented to point to the next
position.
Complexity Analysis
● Time Complexity: O(n), where n is the number of elements in the array. We traverse
the array only once.
● Space Complexity: O(1), as we are modifying the array in-place without using any
extra space.
Edge Cases
● If the array is empty, the function does nothing.
● If there are no zeros, the array remains unchanged.
● If all elements are zeros, the array remains unchanged.
Alternative Approach
Another approach is to count the number of non-zero elements and then fill the array
accordingly:
Algorithm
Python Implementation
def move_zeroes(nums):
count = 0
for num in nums:
if num != 0:
nums[count] = num
count += 1
while count < len(nums):
nums[count] = 0
count += 1
Explanation
● The first loop moves all non-zero elements to the beginning of the array.
● The second loop fills the remaining positions with zeros.
Complexity Analysis
● Time Complexity: O(n), as we traverse the array twice.
● Space Complexity: O(1), since we are modifying the array in-place.
Notes
The two-pointer approach is efficient for solving the "Move Zeroes" problem, providing an
in-place solution with linear time complexity. Understanding and implementing such
algorithms is crucial for optimizing performance in real-world applications.