Taro Logo

Move Zeroes

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+29
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.7K views
Topics:
ArraysTwo Pointers

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Example 2:

Input: nums = [0]
Output: [0]

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array be empty or contain only a single element, and how should we handle those cases?
  2. Could the array contain negative integers, or are we strictly dealing with positive integers and zeroes?
  3. Since the problem specifies doing this in-place, should the function have a specific return type (like void), or does the interviewer expect it to return the modified array reference?
  4. Is there any memory constraint regarding auxiliary space, or is $O(1)$ extra space strictly required beyond the input array?
  5. If the array already contains no zeroes or is already in the correct format, should we still optimize our writes to avoid unnecessary assignments?

Brute Force Solution

Approach

Imagine you have a line of items containing some special empty placeholders and you want to push all the empty placeholders to the very end while keeping the rest of the items in their original relative order. The brute force approach relies on creating a completely separate workspace to rebuild the line from scratch.

Here's how the algorithm would work step-by-step:

  1. Look at the original line of items from the very beginning to the very end.
  2. Every time you spot a regular item that is not an empty placeholder, pick it up and place it into your new workspace.
  3. Once you have checked every single spot in the original line and copied all the regular items over, notice how many empty placeholders were left behind.
  4. Go to the end of your new workspace and fill up all the remaining empty spots with that exact number of placeholders.
  5. Finally, replace the original line with the contents of your new workspace so everything is neatly arranged with all the regular items first and all the placeholders pushed to the back.

Code Implementation

def move_zeroes(number_list):
    # We need a separate workspace to temporarily hold all the non-zero elements in order
    workspace_list = []

    for current_index in range(len(number_list)):
        if number_list[current_index] != 0:
            workspace_list.append(number_list[current_index])

    # Counting missing spots allows us to pad the end with the correct number of zeroes
    zero_count = len(number_list) - len(workspace_list)

    for padding_index in range(zero_count):
        workspace_list.append(0)

    # Copying back is required to modify the original array in place as expected
    for original_index in range(len(number_list)):
        number_list[original_index] = workspace_list[original_index]

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n represent the total number of items in the original line. The first phase requires a complete pass from the beginning to the end to pick up and copy every non-placeholder item into the new workspace. The second phase then fills the remaining spots at the end of the workspace with placeholders, scaling linearly based on the count of those placeholders. Summing these sequential operations yields approximately n plus n total steps. By dropping the constant factor, the overall time complexity simplifies to O(n).
Space Complexity
O(N) – The brute force approach requires a completely separate workspace to rebuild the line from scratch, creating a temporary list that scales directly with the input size N. Every non-placeholder item is copied into this new auxiliary array, meaning the extra memory used grows linearly as N increases. Consequently, this hidden data structure drives the auxiliary space complexity. Finally, filling the remaining spots in this separate workspace does not require any additional memory beyond what was already allocated. Thus, the total extra memory approximates to O(N).

Optimal Solution

Approach

The optimal strategy for this problem is like organizing a line of people by shuffling all the non-zero items forward while keeping them in their original order. By scanning through the line and keeping track of where the next non-zero item belongs, we can neatly group all the zeroes at the very end in a single pass.

Here's how the algorithm would work step-by-step:

  1. Scan through the items from the beginning to the end, looking for anything that is not a zero.
  2. Whenever you find a non-zero item, pick it up and place it neatly at the next available spot near the front of the line.
  3. Keep a mental marker of where that next available spot is so that non-zero items stay packed tightly together in the exact order you found them.
  4. Continue this process until you reach the end of the line, which naturally leaves all the remaining spots empty.
  5. Finally, fill up all those leftover empty spots at the very end with zeroes, completing the rearrangement efficiently in one go.

Code Implementation

def move_zeroes(items_collection):
    next_available_spot = 0

    # Shift all non-zero elements forward to preserve their relative order in the array.
    for current_index in range(len(items_collection)):
        if items_collection[current_index] != 0:
            items_collection[next_available_spot] = items_collection[current_index]
            next_available_spot += 1

    # Fill the remaining trailing positions with zeroes after all non-zeroes are placed.
    for trailing_index in range(next_available_spot, len(items_collection)):
        items_collection[trailing_index] = 0

    # The array is now modified in place with all zeroes pushed to the back.

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single pass through the array of size n to scan for and shift all non-zero elements to their correct positions. A second, independent pass fills the remaining empty spots at the end of the array with zeroes. Each pass scales linearly with the input size n, resulting in roughly 2n total operations. Dropping the constant factor simplifies this directly to O(n).
Space Complexity
O(1) – The algorithm performs all rearrangements in place directly on the input array without allocating any auxiliary data structures such as temporary lists or hash maps. The mental marker described in the strategy corresponds to a single integer pointer variable used to track the next available spot. Because this variable consumes a constant amount of memory regardless of the input size N, the auxiliary space complexity remains strictly constant.

Edge Cases

Empty array or single element array
How to Handle:
The two-pointer approach safely skips the loop or performs no swaps, leaving the array unchanged as required.
Array already contains no zeroes
How to Handle:
The fast pointer will iterate to the end and continuously overwrite elements with themselves without causing issues.
Array consists entirely of zeroes
How to Handle:
The slow pointer remains at the beginning while the fast pointer traverses the entire array, leaving all zeroes intact.
All non-zero elements are at the end of the array
How to Handle:
The pointers will efficiently swap the leading zeroes with the trailing non-zero elements to push all zeroes back.
Array contains alternating zeroes and non-zeroes
How to Handle:
The partition pattern correctly gathers all non-zero elements to the front while preserving their relative order.
Array contains negative numbers
How to Handle:
Since the condition checks strictly for non-zero values, negative numbers are treated identically to positive non-zero integers.
Extremely large array scaling
How to Handle:
The linear time O(n) pass with constant O(1) extra space ensures optimal performance and prevents memory limit issues.
Trailing zeroes already at the end of the array
How to Handle:
The algorithm minimizes unnecessary writes by only swapping or overwriting when a non-zero element precedes a zero.
0/75 completed