Skip to content
Katabench
Try free

Move Zeroes

Easy About 10 min Free, no account needed

Push all zeros to the end while keeping the other values in order.

The brief

Given an integer array nums, return it with all 0s moved to the end while the relative order of the non-zero values is preserved.

The performance bar

The obvious approach finds each zero and shifts everything after it left by one; shifting is O(n) per zero, so an array full of zeros costs O(n2). The hidden test is 100,000 zeros followed by a one, so the per-zero shifting is too slow. You will need a single-pass approach, O(n).

Starter code

C#
using System;

public class Solution
{
    // TODO: return the array with all zeros pushed to the end and non-zero order preserved.
    public int[] MoveZeroes(int[] nums)
    {
        throw new NotImplementedException();
    }
}

How it is graded

Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.

C# coding challenges →

What it practices

Two pointers
Walk a sorted or symmetric sequence from both ends, or fast and slow, instead of checking every pair.

Related katas