← All problems · Pointers & Strings
Find First Unique Byte in a String
Return the first byte occurring exactly once in a length-delimited buffer, or -1.
Implement int first_unique(const unsigned char *s, 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.
Count byte frequencies before scanning again.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
int first_unique(const unsigned char *s, size_t n)
{
size_t counts[256]={0}; for(size_t i=0;i<n;++i)++counts[s[i]]; for(size_t i=0;i<n;++i)if(counts[s[i]]==1)return s[i]; return -1;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
int first_unique(const unsigned char *s, std::size_t n)
{
std::size_t counts[256]={0}; for(std::size_t i=0;i<n;++i)++counts[s[i]]; for(std::size_t i=0;i<n;++i)if(counts[s[i]]==1)return s[i]; return -1;
}
A fixed frequency table avoids dynamic allocation.
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)
{
unsigned char a[]={255,0,255};
CHECK(first_unique((const unsigned char*)"aabbcdd",7)=='c');
CHECK(first_unique((const unsigned char*)"aa",2)==-1);
CHECK(first_unique(a,3)==0);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}