Opening the reading…
Opening the reading…
HASHING › IMPLEMENTARY PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The string is valid when every character that appears contributes the same number of positions. Characters absent from the string do not participate, so their frequency of zero must not be compared with the frequencies of present characters.
Count the occurrences of all 26 lowercase letters. Then scan those counts and use the first positive count as the target frequency. Every later positive count must match it; if none differs, all appearing characters occur equally often.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The first pass processes each of the n characters once, and the second pass examines exactly 26 counters. Since 26 is a fixed constant, O(n + 26) simplifies to O(n), with no input shape that increases the scan beyond these two passes. |
| Space | O(1) extra | The frequency array always contains 26 integers, regardless of n. The returned boolean is required output and is excluded from working memory, so the extra space remains O(1) even for the largest allowed string. |
#include <string>
using namespace std;
class Solution {
public:
bool areOccurrencesEqual(string s) {
int freq[26] = {0};
for (char c : s) {
freq[c - 'a']++;
}
int common = 0;
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
if (common == 0) {
common = freq[i];
} else if (freq[i] != common) {
return false;
}
}
}
return true;
}
};The important guard is freq[i] > 0. It skips letters that never appear, while common == 0 records that no appearing letter has been seen yet. Because the string is non-empty, at least one counter becomes positive, but the same structure also makes the scan's intent explicit: only present characters define the condition.