Move All Zeroes to End of Array in Java with Example

๐Ÿ‘๏ธ 4 Views
|
๐Ÿ“… Jul 20, 2026
|
โฑ๏ธ 5 min read
Move All Zeroes to End of Array in Java with Example

Move Zeroes in Array | Java Interview Question Explained

The Move Zeroes problem is one of the most popular Java array interview questions. It is commonly asked to evaluate your understanding of arrays, in-place algorithms, time complexity, and problem-solving skills. Although the problem appears simple, interviewers expect an optimized solution instead of a straightforward one.

In this tutorial, you'll learn how to solve the Move Zeroes problem using an efficient Two Pointer Technique. We'll understand the logic, perform a dry run, write the Java solution, and analyze its time and space complexity.


Problem Statement

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

Requirements:

  • Modify the original array.
  • Do not create another array.
  • Maintain the order of non-zero elements.

Example 1

Input

[0, 1, 0, 3, 12]

Output

[1, 3, 12, 0, 0]

Example 2

Input

[0, 0, 5, 0, 8, 7]

Output

[5, 8, 7, 0, 0, 0]

Understanding the Problem

The goal is not to sort the array. Instead, we simply move all non-zero elements towards the beginning while preserving their original order. Once every non-zero element has been placed, the remaining positions are filled with zeroes.

Input

0 1 0 3 12

โ†“

Collect Non-Zero Elements

1 3 12

โ†“

Place Them at the Beginning

1 3 12 _ _

โ†“

Fill Remaining Positions

1 3 12 0 0

Naive Approach

A simple solution is to shift elements every time a zero is found. Although this produces the correct output, it performs unnecessary element movements and becomes inefficient for large arrays.

The time complexity of this approach can reach O(nยฒ), making it unsuitable for coding interviews.


Optimized Approach (Two Pointer Technique)

The optimized solution uses a variable named index to track the next position where a non-zero element should be placed.

  1. Traverse the array once.
  2. If the current element is not zero, copy it to index.
  3. Increment index.
  4. After the traversal, fill the remaining positions with zeroes.

Since every element is visited only once, this approach is both fast and memory-efficient.


Java Solution

public class MoveZeroes {

    public static void moveZeroes(int[] nums) {

        int index = 0;

        // Move all non-zero elements
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[index] = nums[i];
                index++;
            }
        }

        // Fill remaining positions with zeroes
        while (index < nums.length) {
            nums[index] = 0;
            index++;
        }
    }

    public static void main(String[] args) {

        int[] nums = {0, 1, 0, 3, 12};

        moveZeroes(nums);

        for (int num : nums) {
            System.out.print(num + " ");
        }
    }
}

Output

1 3 12 0 0

Dry Run

Input:

[0, 1, 0, 3, 12]
Current Element Action Array Index
0 Skip [0,1,0,3,12] 0
1 Move to index 0 [1,1,0,3,12] 1
0 Skip [1,1,0,3,12] 1
3 Move to index 1 [1,3,0,3,12] 2
12 Move to index 2 [1,3,12,3,12] 3

After the first loop finishes, all non-zero elements are in the correct order. The remaining positions are then replaced with zeroes.

Final Output

[1, 3, 12, 0, 0]

Code Explanation

  • Create an index variable initialized to 0.
  • Traverse the array only once.
  • Whenever a non-zero value is found, copy it to nums[index].
  • Increment index after every non-zero element.
  • Fill the remaining positions with zeroes.

Time Complexity

O(n)

The algorithm scans the array only once, making it highly efficient for both small and large input sizes.


Space Complexity

O(1)

No additional array or collection is created. The operation is performed directly on the original array.


Why This Solution Is Preferred

  • Uses an in-place algorithm.
  • Maintains the order of non-zero elements.
  • Requires only one traversal.
  • Uses constant extra space.
  • Suitable for coding interviews.
Interview Tip: If you create another array to solve this problem, the interviewer will usually ask you to optimize it. The expected solution is the Two Pointer Technique with O(n) time complexity and O(1) extra space.

Common Mistakes

  • Creating an extra array instead of modifying the original array.
  • Changing the order of non-zero elements.
  • Using nested loops, resulting in O(nยฒ) time complexity.
  • Forgetting to fill the remaining positions with zeroes.

Frequently Asked Questions (FAQ)

Can this problem be solved without another array?

Yes. The optimized solution modifies the original array in-place.

Which algorithm is used?

The Two Pointer Technique is commonly used.

What is the time complexity?

The time complexity is O(n).

What is the space complexity?

The space complexity is O(1).


Related Java Interview Questions

  • Two Sum
  • Remove Duplicates from Sorted Array
  • Rotate Array
  • Best Time to Buy and Sell Stock
  • Merge Sorted Arrays
  • Product of Array Except Self

Conclusion

The Move Zeroes problem is an excellent Java interview question because it tests your understanding of array manipulation, in-place algorithms, and optimization techniques. While a brute-force solution is easy to implement, the Two Pointer Technique provides the optimal solution with O(n) time complexity and O(1) extra space.

Mastering problems like this will strengthen your problem-solving skills and prepare you for Java coding interviews at product-based and service-based companies.