Challenge - 5 Problems
Character Frequency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of character frequency count in a string
What is the output of the following C code that counts character frequencies in a string?
DSA C
#include <stdio.h> #include <string.h> int main() { char str[] = "hello world"; int freq[256] = {0}; for (int i = 0; i < strlen(str); i++) { freq[(unsigned char)str[i]]++; } for (int i = 0; i < 256; i++) { if (freq[i] > 0) { printf("%c:%d ", i, freq[i]); } } return 0; }
Attempts:
2 left
💡 Hint
Count each character's occurrences carefully, including spaces.
✗ Incorrect
The string "hello world" has 1 'h', 1 'e', 3 'l's, 2 'o's, 2 spaces, 1 'w', 1 'r', and 1 'd'.
🧠 Conceptual
intermediate1:30remaining
Understanding character frequency array size
Why is the frequency array usually declared with size 256 when counting characters in C?
Attempts:
2 left
💡 Hint
Think about the range of unsigned char values.
✗ Incorrect
The array size 256 covers all possible values of an unsigned char (0 to 255), which includes all ASCII and extended ASCII characters.
🔧 Debug
advanced2:00remaining
Identify the error in character frequency counting code
What error will the following code produce when counting character frequencies?
DSA C
#include <stdio.h> #include <string.h> int main() { char str[] = "abcabc"; int freq[128]; for (int i = 0; i < strlen(str); i++) { freq[(int)str[i]]++; } for (int i = 0; i < 128; i++) { if (freq[i] > 0) { printf("%c:%d ", i, freq[i]); } } return 0; }
Attempts:
2 left
💡 Hint
Check if freq array elements are initialized before incrementing.
✗ Incorrect
The freq array is not initialized, so it contains garbage values. Incrementing them causes undefined behavior and likely wrong output or runtime errors.
❓ Predict Output
advanced2:00remaining
Output of frequency count with non-alphabet characters
What is the output of this C code counting frequencies including digits and punctuation?
DSA C
#include <stdio.h> #include <string.h> int main() { char str[] = "a1!a2!"; int freq[256] = {0}; for (int i = 0; i < strlen(str); i++) { freq[(unsigned char)str[i]]++; } for (int i = 0; i < 256; i++) { if (freq[i] > 0) { printf("%c:%d ", i, freq[i]); } } return 0; }
Attempts:
2 left
💡 Hint
Check the order of characters printed by increasing ASCII code.
✗ Incorrect
Characters are printed in ASCII order: '!' (33), '1' (49), '2' (50), 'a' (97). Frequencies: '!'=2, '1'=1, '2'=1, 'a'=2.
🧠 Conceptual
expert2:30remaining
Memory optimization for character frequency counting
Which approach best reduces memory usage when counting frequencies of only lowercase English letters in a large text?
Attempts:
2 left
💡 Hint
Focus on the smallest fixed-size array that covers only needed characters.
✗ Incorrect
Using an int array of size 26 indexed by (character - 'a') uses minimal memory and is efficient for lowercase letters only.
