</>EmbeddedInterview
← All problems · Arrays & Searching

Move All Zeroes to the End of an Array

Easy

Move every zero to the end in place while keeping the relative order of nonzero elements. Use O(1) extra space. Implement void move_zeroes(int *a, size_t n).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Compact nonzero elements, then fill the rest with zero.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>

void move_zeroes(int *a, size_t n)
{
    size_t j=0;
    for(size_t i=0;i<n;++i)if(a[i]!=0)a[j++]=a[i];
    while(j<n)a[j++]=0;
}

A write index never exceeds the read index, so the forward compaction cannot overwrite unread elements.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    int a[]={0,1,0,3,12}, expected[]={1,3,12,0,0}, b[]={0,0}, c[]={1,-2};
    CHECK((move_zeroes(a,5),memcmp(a,expected,sizeof a)==0));
    CHECK((move_zeroes(b,2),b[0]==0 && b[1]==0));
    CHECK((move_zeroes(c,2),c[0]==1 && c[1]==-2));
    CHECK((move_zeroes(NULL,0),1));
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}