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
abAdCplaNE
2aAbCFirst 2 lowercase letters: 'a', 'b' First 2 uppercase letters: 'A', 'C' Alternating output: 'a' (lower) + 'A' (upper) + 'b' (lower) + 'C' (upper) = 'aAbC'
cRICkEt
3cRkItCFirst 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;
}The C solution uses character arrays and the standard library functions islower() and isupper() to identify letter cases.
- Read the string using
fgets()and remove the trailing newline - Use two character arrays to store lowercase and uppercase letters separately
- Iterate through the string twice: once to collect lowercase letters, once for uppercase
- 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.