easy
1 views

String Alphabet Count

Count the frequency of each alphabet character in a given string and display them in alphabetical order.

Understand the Problem

Problem Statement

String Alphabet Count: Given a string S with only alphabets, print the alphabet and its count as shown in the Example Input/Output section.

Constraints

  • 1 <= Length of S <= 100
  • String S contains only alphabetic characters (a-z, A-Z)
  • Case sensitivity: treat uppercase and lowercase as distinct characters
  • Output must be sorted alphabetically by character

Examples

Example 1
Input
apple
Output
a1 e1 l1 p2
Explanation

In 'apple': 'a' appears 1 time, 'e' appears 1 time, 'l' appears 1 time, 'p' appears 2 times. Output is sorted alphabetically.

Example 2
Input
hello
Output
e1 h1 l2 o1
Explanation

In 'hello': 'e' appears 1 time, 'h' appears 1 time, 'l' appears 2 times, 'o' appears 1 time. Output is sorted alphabetically.

Example 3
Input
aabbcc
Output
a2 b2 c2
Explanation

In 'aabbcc': each character 'a', 'b', and 'c' appears exactly 2 times. Output is sorted alphabetically.

Solution

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

int compare(const void *a, const void *b) {
    return (*(char*)a - *(char*)b);
}

int main() {
    char s[101];
    fgets(s, sizeof(s), stdin);
    
    // Remove newline if present
    int len = strlen(s);
    if (s[len-1] == '\n') {
        s[len-1] = '\0';
        len--;
    }
    
    // Create sorted copy for ordering
    char sorted[101];
    strcpy(sorted, s);
    qsort(sorted, len, sizeof(char), compare);
    
    // Create unique character array
    char unique[101];
    int unique_count = 0;
    
    for (int i = 0; i < len; i++) {
        int found = 0;
        for (int j = 0; j < unique_count; j++) {
            if (unique[j] == sorted[i]) {
                found = 1;
                break;
            }
        }
        if (!found) {
            unique[unique_count++] = sorted[i];
        }
    }
    
    // Print results
    for (int i = 0; i < unique_count; i++) {
        int count = 0;
        for (int j = 0; j < len; j++) {
            if (s[j] == unique[i]) {
                count++;
            }
        }
        printf("%c%d", unique[i], count);
        if (i < unique_count - 1) {
            printf(" ");
        }
    }
    
    return 0;
}
Time:O(n log n) due to sorting
Space:O(n) for storing sorted and unique character arrays
Approach:

C Solution Explanation:

1. Read input string using fgets() and remove trailing newline

2. Create a sorted copy of the string using qsort() to determine output order

3. Extract unique characters from sorted string using nested loops

4. For each unique character, count occurrences in original string

5. Print character and count, with spaces between pairs

6. Uses standard C library functions for sorting and string manipulation

Visual Explanation

Loading diagram...
String Alphabet Count | Letuscrack