New Line – Repeated Characters
Split a string into substrings at positions where characters occur repeatedly
Understand the Problem
Problem Statement
The program must accept a string S as the input. The program must split the string S wherever a character occurs repeatedly(i.e., two or more occurrences). Then the program must print the substrings as the output.
Constraints
- 2 <= Length of S <= 100
- String S contains only alphabetic characters (case-sensitive)
- Each character can appear multiple times in the string
- Output substrings must be printed on separate lines
Examples
skillrackskil
lrac
kThe string 'skillrack' is split at positions where characters repeat. The character 'l' appears at positions 3 and 4 (0-indexed), and 'k' appears at positions 0 and 8. The substrings are: 'skil' (before first 'l'), 'lrac' (between 'l' and 'k'), and 'k' (after the last 'k').
ENvironmentENvironme
ntThe string 'ENvironment' has the character 'n' appearing at positions 1 and 8 (0-indexed). The string is split into 'ENvironme' (before the repeated 'n') and 'nt' (after the repeated 'n').
abcdabcdefgeabcd
a
b
c
defg
eThe string 'abcdabcdefge' has multiple repeated characters: 'a' at positions 0 and 4, 'b' at positions 1 and 5, 'c' at positions 2 and 6, and 'e' at positions 7 and 11. The string is split at each repeated character position, creating substrings: 'abcd', 'a', 'b', 'c', 'defg', and 'e'.
Solution
#include <stdio.h>
#include <string.h>
int main() {
char s[101];
fgets(s, sizeof(s), stdin);
// Remove newline character if present
int len = strlen(s);
if (s[len-1] == '\n') {
s[len-1] = '\0';
len--;
}
int splitPoints[100];
int splitCount = 0;
int charCount[256] = {0}; // ASCII character frequency
// Find split points where characters repeat
for (int i = 0; i < len; i++) {
charCount[(unsigned char)s[i]]++;
if (charCount[(unsigned char)s[i]] == 2) {
splitPoints[splitCount++] = i;
}
}
// Print substrings
int start = 0;
for (int i = 0; i < splitCount; i++) {
for (int j = start; j < splitPoints[i]; j++) {
printf("%c", s[j]);
}
printf("\n");
start = splitPoints[i];
}
// Print last substring
for (int j = start; j < len; j++) {
printf("%c", s[j]);
}
printf("\n");
return 0;
}Step-by-step explanation:
- Read the input string using fgets() and remove trailing newline
- Create an array splitPoints to store positions where splits should occur
- Use a frequency array charCount to track character occurrences
- Iterate through the string, incrementing character counts
- When a character count reaches 2, record its position as a split point
- Print substrings by iterating between consecutive split points
- Handle the final substring from the last split point to the end
The solution efficiently tracks character frequencies using an array indexed by ASCII values, ensuring O(1) lookup time for character counting.