Top 5 Array Interview Problems in Java (With Real-World Solutions)

7.18K 0 0 0 0

Problem #2: Move All Zeroes to the End of the Array (In-Place)

🧠 Problem Statement

Given:
An array of integers.

Task:
Move all the 0s to the end of the array while maintaining the relative order of non-zero elements.
Do this in-place without making a copy of the array.


🧾 Sample Input/Output

Input:
int[] arr = {0, 1, 0, 3, 12};
Output:
[1, 3, 12, 0, 0]

Input:
int[] arr = {1, 2, 0, 0, 4, 5};
Output:
[1, 2, 4, 5, 0, 0]


🔍 Naive Approach: Using Extra Array

This violates the “in-place” constraint — but it’s easy to start with.

public static int[] moveZeroesCopy(int[] arr) {

    int[] result = new int[arr.length];

    int index = 0;

    for (int num : arr) {

        if (num != 0) {

            result[index++] = num;

        }

    }

    // zeros are already 0 by default in new array

    return result;

}

Space Complexity: O(n)


Optimal In-Place Solution (Two Pointers)

Use one pointer to track the current position to place non-zero values.

public static void moveZeroes(int[] arr) {

    int index = 0;

 

    // Step 1: Move all non-zero values forward

    for (int i = 0; i < arr.length; i++) {

        if (arr[i] != 0) {

            arr[index++] = arr[i];

        }

    }

 

    // Step 2: Fill the rest with zeroes

    while (index < arr.length) {

        arr[index++] = 0;

    }

}


🧠 Explanation

  1. Iterate and copy non-zero values to the front (index keeps track).
  2. After the loop, fill the rest of the array with zeroes starting from index.

🔁 Real Interview Follow-Up: One-Pass Swap

public static void moveZeroesSwap(int[] arr) {

    int lastNonZeroFoundAt = 0;

 

    for (int i = 0; i < arr.length; i++) {

        if (arr[i] != 0) {

            int temp = arr[lastNonZeroFoundAt];

            arr[lastNonZeroFoundAt] = arr[i];

            arr[i] = temp;

            lastNonZeroFoundAt++;

        }

    }

}

Preserves relative order
Swaps in-place
One-pass


️ Edge Cases to Consider

Input

Output

Notes

[0, 0, 0]

[0, 0, 0]

All zeroes

[1, 2, 3]

[1, 2, 3]

No change needed

[]

[]

Empty array

[0, 1]

[1, 0]

Smallest non-trivial case


📈 Time & Space Complexity

Operation

Value

Time

O(n)

Space

O(1) — In-place


🧨 Interview Variants

  1. "Move all zeroes to the front instead"
    Reverse logic — fill from back to front
  2. "Do it in a single pass without using extra variables"
    Use XOR swap trick (not preferred for clarity)
  3. "Count minimum number of swaps to move zeroes to end"
    Count how many times zero and non-zero indices swap

Summary


Step

Description

Two-pointer strategy

Place non-zero at next available slot

In-place operation

No extra array required

One-pass swap optimization

Faster for large arrays

Preserves order

Interviewer will often test for this too

Back

FAQs


1. Why are array problems so common in Java interviews?

Because they test core programming logic, data handling, loops, and algorithm efficiency.

2. What’s the difference between int[] and Integer[] in Java?

int[] is a primitive array; Integer[] is an array of objects (wrappers). The latter allows null values and works with collections.

3. Is it better to use Arrays or ArrayLists in interviews?

For fixed-size problems, use arrays. For dynamic data, ArrayList is better — but stick to arrays unless otherwise asked

4. What are common pitfalls in Java array questions?

Index out of bounds, mutating arrays while iterating, and forgetting that Java arrays have fixed size.

5. How do I remove duplicates from a Java array?

Use a Set for uniqueness or sort the array first and remove duplicates in-place using two pointers.

6. When should I use the two-pointer technique?

It’s great for sorted arrays, especially for problems involving pair sums, removing duplicates, and reversing data in-place.

7. How can I rotate an array in Java?

Use reversal techniques or cyclic replacements to do it in O(1) space.

8. What’s the time complexity of array search vs binary search?

Linear search = O(n); binary search = O(log n), but only on sorted arrays.

9. How do I handle negative numbers or large input arrays?

Always consider edge cases: empty arrays, one element, all duplicates, etc. Optimize with hashmaps or prefix sums where needed.

10. What libraries or classes help with arrays in Java?

Use Arrays.sort(), System.arraycopy(), Arrays.toString(), and Collections when applicable — but show the manual solution first in interviews.