C Online Compiler
Example: Find First Non-Repeating Character (Frequency Array) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find First Non-Repeating Character (Frequency Array) #include <stdio.h> #include <string.h> // For strlen #define MAX_CHARS 256 // Assuming ASCII characters int main() { char str[] = "aabbcdeff"; // Example string int len = strlen(str); int freq[MAX_CHARS] = {0}; // Initialize all frequencies to 0 // Step 1: First pass - Populate the frequency array // Iterate through the string and count occurrences of each character for (int i = 0; i < len; i++) { // Increment count for the character at its ASCII value index freq[(unsigned char)str[i]]++; } char firstNonRepeating = '\0'; // Initialize with null character // Step 2: Second pass - Find the first character with frequency 1 // Iterate through the string again, in order, to find the first character // whose count in the freq array is 1. for (int i = 0; i < len; i++) { if (freq[(unsigned char)str[i]] == 1) { firstNonRepeating = str[i]; break; // Found the first non-repeating, no need to continue } } // Step 3: Print the result if (firstNonRepeating != '\0') { printf("The first non-repeating character is: %c\n", firstNonRepeating); } else { printf("No non-repeating character found.\n"); } return 0; }
Output
Clear
ADVERTISEMENTS