Skip to main content

Move Zeroes In Place in Java and Python

Move zeroes to the end of an array in place while preserving the order of nonzero values. Learn the two-pointer solution in Java and Python.

Problem and input contract

Pass a mutable sequence of integers. Both implementations modify it in place and return no value. The sequence retains its original length, with all nonzero values in their original relative order.

[0, 3, 0, 2] becomes [3, 2, 0, 0]. [0, 0] and [-2, 4] stay unchanged. An empty array remains empty.

Worked example

[0, 3, 0, 2] becomes [3, 2, 0, 0].

Skip the first 0. Copy 3 into index 0, skip the next 0, then copy 2 into index 1. At that point write is 2, so fill indices 2 and 3 with zero.

How the solution works

The write index never moves ahead of the read index. Every nonzero value is copied forward in encounter order, then the remaining cells are filled with zeros.

Each write lands at or before the position being read. This keeps unread values intact and preserves the original order of the nonzero numbers.

Python solution

def move_zeroes(nums):
    write = 0
    for value in nums:
        if value != 0:
            nums[write] = value
            write += 1
    for index in range(write, len(nums)):
        nums[index] = 0

Java solution

class Solution {
    static void moveZeroes(int[] nums) {
        int write = 0;
        for (int value : nums) {
            if (value != 0) nums[write++] = value;
        }
        while (write < nums.length) nums[write++] = 0;
    }
}

Approaches and complexity

You can build a separate list of nonzero values and copy it back before filling zeros, using O(n) temporary storage. The two-pointer solution has one pass over the input followed by a pass over the tail, taking O(n) time and O(1) auxiliary space.

Approach comparison
ApproachTimeAuxiliary spaceAdvantageLimitationUse case
Temporary listO(n)O(n)StraightforwardStores a second sequenceMemory is plentiful
Two pointersO(n)O(1)In-place and stableMay rewrite some cellsMemory-constrained inputs

Common mistakes and interview follow-up

Advance the write index only when keeping a value. Filling the suffix after the scan prevents unread values from being overwritten. If writes are expensive, discuss how to skip self-assignments.

Related practice: Find Two Numbers That Add to a Target.

Comments

Popular posts from this blog

Minimum Window Substring: Efficient Algorithm for Finding the Shortest Substring

The Minimum Window Substring problem is a classic string manipulation challenge that tests our algorithmic skills. In this blog, we will explore an efficient solution to find the minimum window substring in a given string. We will provide implementation examples in both Java and Python, enabling you to grasp the concepts and apply them to your own coding projects.   Understanding the Problem: Given a string and a target pattern, our objective is to find the minimum window substring in the given string that contains all the characters of the target pattern. The minimum window substring refers to the shortest possible substring that satisfies this condition.   Approach: To solve the Minimum Window Substring problem, we can use the sliding window technique. This approach involves maintaining a window of characters in the string and adjusting its size based on certain conditions. The key steps of the algorithm are as follows: Create two pointers, left and right, to define the windo...

Longest Palindromic Substring: Explained with Java and Python Code

The Longest Palindromic Substring problem is a classic challenge in the realm of string manipulation. In this blog, we will delve into the intricacies of finding the longest palindromic substring in a given string. Through a step-by-step approach and illustrative examples, you will gain a comprehensive understanding of the problem and learn how to solve it efficiently.   Understanding the Problem: A palindrome is a string that reads the same forward and backward. The Longest Palindromic Substring problem requires finding the longest substring within a given string that is also a palindrome. Our goal is to determine the length of this substring and return the substring itself.   Approach: To solve the Longest Palindromic Substring problem, we can employ a dynamic programming approach or use the expanding around center technique. Here, we will explore the dynamic programming approach. Create a boolean table, dp, of size [n][n] (where n is the length of the input string) to store ...