← All problems · Arrays & Searching
Find the Missing Number from 0 to N
An array of n distinct values from 0 through n has exactly one missing value. Return it in O(n) time and O(1) extra space.
Implement uint32_t missing(const uint32_t *a, uint32_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.
XOR the expected and actual values.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
uint32_t missing(const uint32_t *a, uint32_t n)
{
uint32_t x=n;
for(uint32_t i=0;i<n;++i)x ^= i ^ a[i];
return x;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
std::uint32_t missing(const std::uint32_t *a, std::uint32_t n)
{
std::uint32_t x=n;
for(std::uint32_t i=0;i<n;++i)x ^= i ^ a[i];
return x;
}
Matching values cancel, leaving the missing value. This avoids overflow possible with the arithmetic-sum approach in the original exercise.
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)
{
uint32_t a[]={0,4,1,3}, b[]={1,2,3}, c[]={2,0,1};
CHECK(missing(a,4)==2);
CHECK(missing(b,3)==0);
CHECK(missing(c,3)==3);
CHECK(missing(NULL,0)==0);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}