medium
0 views
Alphabet Count – Repeated String
Count occurrences of a specific alphabet in a string that has been repeated to reach a specified length
Understand the Problem
Problem Statement
A string S is passed as input to the program. The string S is repeated till the repeated string R is of length N. The program must print the count of a specific alphabet A which is passed as the input in the repeated string R.
Constraints
- 1 <= Length of S <= 50
- 1 <= N <= 9999999
- A is from a to z
Examples
Example 1
Input
abcd
10
bOutput
3Explanation
abcd when repeated till length 10 is abcdabcdab in which the alphabet b occurs 3 times. The string 'abcd' has 1 occurrence of 'b'. We have 2 complete repetitions (8 characters) plus 2 more characters 'ab'. Total = 2×1 + 1 = 3.
Solution
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char s[51];
long long N;
char A;
// Read inputs
scanf("%s", s);
scanf("%lld", &N);
scanf(" %c", &A); // Space before %c to consume newline
int len = strlen(s);
// Count occurrences of A in original string
int count_in_original = 0;
for (int i = 0; i < len; i++) {
if (s[i] == A) {
count_in_original++;
}
}
// Calculate complete repetitions and remainder
long long complete_repetitions = N / len;
int remainder = N % len;
// Count in complete repetitions
long long total_count = complete_repetitions * count_in_original;
// Count in partial repetition (if any)
for (int i = 0; i < remainder; i++) {
if (s[i] == A) {
total_count++;
}
}
printf("%lld", total_count);
return 0;
}Time:O(len(S)) - We only iterate through the original string twice: once to count occurrences and once for the remainder
Space:O(len(S)) - We store the original string, which is at most 50 characters
Approach:
C Solution Logic:
- Read the string S, target length N, and alphabet A
- Calculate length of original string
- Count how many times A appears in the original string by iterating through it
- Calculate complete repetitions using integer division: N / len(S) <5>Calculate remainder characters using modulo: N % len(S)<6>Count total occurrences: complete_repetitions × count_in_original<7>For remaining characters, count occurrences in the prefix of original string<8>Output the final count
Visual Explanation
Loading diagram...