How to Determine if a String Only Contains Unique Characters in C

  • Home /
  • Blog Posts /
  • How to Determine if a String Only Contains Unique Characters in C

The challenge

Write a program to determine if a string contains only unique characters. Return true if it does and false otherwise.

The string may contain any of the 128 ASCII characters. Characters are case-sensitive, e.g. ‘a’ and ‘A’ are considered different characters.

The solution in C

Option 1:

int has_unique_chars(const char *str) {
  int mask[128]={0};
  while (*str) if (++mask[*str++]>1) return 0;
  return 1;
}

Option 2:

#include <limits.h>

_Bool has_unique_chars(const char *str) {
    char hit[CHAR_MAX + 1] = {0};
    while (*str) {
        if (*str < 0) { str++; continue; }
        if (hit[*str]) return 0;
        hit[*str++] = 1;
    }
    return 1;
}

Option 3:

#include <stdbool.h>
#include <string.h>
#include <stdio.h>

bool has_unique_chars(const char *str) {
  size_t len = strlen(str);
  char *list = malloc(len);
  for (int i = 0; i < len; i++) {
    for (int z = 0; z < i; z++) {  
      if (*(list + z) == str[i]) {
        return false;  
      }
    }
    *(list + i) = str[i];
  }
  return true;
}

Test cases to validate our solution

#include <criterion/criterion.h>

bool has_unique_chars(const char *str);

Test(has_unique_chars, test_example) {
    cr_assert_not(has_unique_chars("  nAa"));
    cr_assert(has_unique_chars("abcde"));
    cr_assert_not(has_unique_chars("++-"));
    cr_assert(has_unique_chars("AaBbC"));
}