A. Loop condition should be i < str.length, not i <= str.length
B. freq should be initialized as an array, not object
C. Use let instead of const for freq
D. Missing semicolon after freq[ch] assignment
Solution
Step 1: Check loop range
Loop runs from i = 0 to i <= str.length, which means i goes up to str.length (3 for 'abc').
Step 2: Identify out-of-bounds access
str[3] is undefined, so freq[undefined] is updated causing wrong key.
Final Answer:
Loop condition should be i < str.length, not i <= str.length -> Option A
Quick Check:
Array index max is length - 1 [OK]
Hint: Use i < length to avoid out-of-bounds errors [OK]
Common Mistakes:
Using <= instead of < in loop
Initializing freq as array instead of object
Ignoring undefined character access
5. Given the string "aabbccddeeffgghhii", which code snippet correctly counts only characters that appear more than once and stores them in freq object?
hard
A. const freq = {};
for (const ch of str) {
freq[ch] = (freq[ch] || 0) + 1;
}
const filtered = {};
for (const ch in freq) {
if (freq[ch] > 1) filtered[ch] = freq[ch];
}
B. const freq = {};
for (const ch of str) {
if (freq[ch]) freq[ch]++;
else freq[ch] = 1;
}
for (const ch in freq) {
if (freq[ch] < 2) freq[ch] = 0;
}
C. const freq = {};
for (const ch of str) {
freq[ch] = 1;
}
for (const ch in freq) {
if (freq[ch] > 1) delete freq[ch];
}
D. const freq = {};
for (const ch of str) {
freq[ch] = (freq[ch] || 0) + 1;
}
for (const ch in freq) {
if (freq[ch] <= 1) delete freq[ch];
}
Solution
Step 1: Count all character frequencies
Use freq[ch] = (freq[ch] || 0) + 1 to count all characters.
Step 2: Delete characters with frequency <= 1 from freq
Iterate and delete keys where freq[ch] <= 1 to leave only duplicates in freq.
Final Answer:
Code snippet that counts all then deletes singles from freq -> Option D
Quick Check:
Delete freq <= 1 from freq [OK]
Hint: Count all, then delete characters with count <= 1 [OK]
Common Mistakes:
Deleting keys while iterating freq object
Setting frequency to 0 instead of removing
Overwriting counts incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.