Example of the string 'swiss' with the first unique character 'w' highlighted, while 's' is repeated.

Introduction

Finding the first non-repeated (unique) character in a string is a simple yet important problem in programming. In this task, you need to find the first character in a string that doesn’t repeat.

For example, in the string “swiss,” the first unique character is ‘w’. It appears only once, while ‘s’ repeats. In contrast, in the string “hello,” the first unique character is ‘h’. The characters ‘e’ and ‘l’ repeat. Therefore, finding the first unique character helps solve similar problems in programming.

This problem helps you practice basic C programming skills like working with strings, arrays, loops, and conditionals.

Code

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

char firstUniqueChar(char str[]) {
    int count[256] = {0};  // Array to count occurrences of each character

    // Count the frequency of each character
    for (int i = 0; str[i] != '\0'; i++) {
        count[str[i]]++;  // Increment the count for each character
    }

    // Find the first character that appears only once
    for (int i = 0; str[i] != '\0'; i++) {
        if (count[str[i]] == 1) {
            return str[i];  // Return the first unique character
        }
    }

    return '\0';  // If no unique character is found, return '\0'
}

int main() {
    char str[] = "swiss";  // Example string
    char result = firstUniqueChar(str);

    // Output the result
    if (result != '\0') {
        printf("The first unique character is: %c\n", result);
    } else {
        printf("No unique character found.\n");
    }

    return 0;
}

Input

The input is a string. For example:

  • "swiss"

Output

The program will print the first character that is unique (appears only once).

For the input "swiss", the output will be:

The first unique character is: w

If there is no unique character (i.e., all characters repeat), the output will be:

No unique character found.

Explanation

Count Array:
We use an array count[256] to count how many times each character appears in the string. Each index of the array corresponds to an ASCII value of a character.

Counting Occurrences:
In the first loop, we go through each character of the string and increment its count in the count array.

Finding the First Unique Character:
After counting, we go through the string again and check if a character appears only once (i.e., count[str[i]] == 1). The first such character is the result.

Edge Case:
If there are no unique characters (i.e., all characters repeat), the program will print “No unique character found.”

Conclusion

This simple problem helps you practice basic C concepts like arrays, loops, and conditionals. The solution uses a counting method, which makes it efficient with a time complexity of O(n), where n is the length of the string.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights