00:00

Problem Statement

Input/Output Examples

Visual Explanation

The write index never passes the read index, so no value is overwritten before it has been read. That is what makes the in-place copy safe.

Approaches

Both approaches use two indexes in one array. The first copies then fills; the second swaps as it goes.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. Both approaches read each element once and use two indexes.

Interview Tips and Recommended Approach

  • Keep the order. Swapping zeros with the last element is faster to write but breaks the order of non-zero values.
  • Explain why it is safe. The write index is never ahead of the read index.
  • Generalise it. The same pattern removes all occurrences of any value in place.
  • Count writes if asked. The swap version avoids rewriting values that are already in place.

Recommended Approach: Write Index, Then Fill

Why: it keeps the non-zero values in order, works in place and is the simplest two-index pattern to explain.