medium
1 views

Expand Alphabets

Given a string containing alternating alphabets and their counts, expand each alphabet by repeating it according to its count.

Understand the Problem

Problem Statement

Problem: Given a string S with alphabets and their count, repeat the alphabets based on their count and print the value as the output.

Constraints

  • 1 ≤ Length of S ≤ 100
  • Input string contains only lowercase alphabets followed by their counts (digits)
  • Each alphabet is followed by exactly one or more digits representing its count
  • Alphabets and counts alternate in the input string
  • Count values are positive integers

Examples

Example 1
Input
a2c5z4
Output
aaccccczzzz
Explanation

a appears 2 times, c appears 5 times, z appears 4 times. So the output is 'aa' + 'ccccc' + 'zzzz' = 'aaccccczzzz'.

Example 2
Input
x3y1z2
Output
xxxyz
Explanation

x appears 3 times, y appears 1 time, z appears 2 times. So the output is 'xxx' + 'y' + 'zz' = 'xxxyz'.

Example 3
Input
p10
Output
pppppppppp
Explanation

p appears 10 times. So the output is 'p' repeated 10 times = 'pppppppppp'.

Solution

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

int main() {
    char s[101];
    fgets(s, sizeof(s), stdin);
    
    int len = strlen(s);
    if (s[len-1] == '\n') {
        s[len-1] = '\0';
        len--;
    }
    
    char current_char = '\0';
    int count = 0;
    
    for (int i = 0; i < len; i++) {
        if (isalpha(s[i])) {
            // If we have a previous character with count, print it
            if (current_char != '\0' && count > 0) {
                for (int j = 0; j < count; j++) {
                    printf("%c", current_char);
                }
            }
            // Set new character
            current_char = s[i];
            count = 0;
        } else if (isdigit(s[i])) {
            // Build the count
            count = count * 10 + (s[i] - '0');
        }
    }
    
    // Print the last character with its count
    if (current_char != '\0' && count > 0) {
        for (int j = 0; j < count; j++) {
            printf("%c", current_char);
        }
    }
    
    printf("\n");
    return 0;
}
Time:O(n)
Space:O(1)
Approach:

C Solution Explanation:

  1. Read input string using fgets()
  2. Remove newline character if present
  3. Use a state machine approach with variables current_char and count
  4. Iterate through each character:
    • If it's an alphabet: print previous character (if any) with its count, then set current_char to this new character
    • If it's a digit: build the count by multiplying by 10 and adding current digit
  5. After loop, print the last character with its count
  6. Time complexity: O(n) where n is string length
  7. Space complexity: O(1) excluding input storage

Visual Explanation

Loading diagram...