medium
1 views

Alternate Lower Case & Upper Case

Print the first N lowercase and N uppercase alphabets from a string alternately

Understand the Problem

Problem Statement

Given a string S and an integer N, extract the first N lowercase alphabets and the first N uppercase alphabets from the string and print them alternately.

Note: The input string is guaranteed to contain at least N lowercase alphabets and N uppercase alphabets.

Constraints

  • 2 ≤ Length of S ≤ 1000
  • 1 ≤ N ≤ 100
  • String S contains at least N lowercase and N uppercase alphabets
  • String S may contain other characters besides alphabets

Examples

Example 1
Input
abAdCplaNE
2
Output
aAbC
Explanation

First 2 lowercase letters: 'a', 'b' First 2 uppercase letters: 'A', 'C' Alternating output: 'a' (lower) + 'A' (upper) + 'b' (lower) + 'C' (upper) = 'aAbC'

Example 2
Input
cRICkEt
3
Output
cRkItC
Explanation

First 3 lowercase letters: 'c', 'k', 't' First 3 uppercase letters: 'R', 'I', 'C' Alternating output: 'c' + 'R' + 'k' + 'I' + 't' + 'C' = 'cRkItC'

Solution

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

int main() {
    char s[1001];
    int n;
    
    // Read input
    fgets(s, sizeof(s), stdin);
    s[strcspn(s, "\n")] = 0; // Remove newline
    scanf("%d", &n);
    
    char lower[101], upper[101];
    int lower_count = 0, upper_count = 0;
    
    // Extract first N lowercase letters
    for (int i = 0; s[i] != '\0' && lower_count < n; i++) {
        if (islower(s[i])) {
            lower[lower_count++] = s[i];
        }
    }
    
    // Extract first N uppercase letters
    for (int i = 0; s[i] != '\0' && upper_count < n; i++) {
        if (isupper(s[i])) {
            upper[upper_count++] = s[i];
        }
    }
    
    // Print alternately
    for (int i = 0; i < n; i++) {
        printf("%c", lower[i]);
        printf("%c", upper[i]);
    }
    
    return 0;
}
Time:O(len(S)) where len(S) is the length of the input string
Space:O(N) for storing the extracted letters (constant space since N ≤ 100)
Approach:

The C solution uses character arrays and the standard library functions islower() and isupper() to identify letter cases.

  1. Read the string using fgets() and remove the trailing newline
  2. Use two character arrays to store lowercase and uppercase letters separately
  3. Iterate through the string twice: once to collect lowercase letters, once for uppercase
  4. Print the letters alternately in a single loop that runs N times

The solution efficiently uses O(1) extra space (fixed-size arrays) and O(len(S)) time complexity.

Visual Explanation

Loading diagram...