- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 63 lines of C++ from the credited upstream file 2168.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 5 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int equalDigitFrequency(string s) {4 vector<vector<int>> counts; 5 vector<int> count(10);6 vector<long> pows{1}; 7 8 9 vector<long> hash{0};10 unordered_set<int> seen;11 12 for (const char c : s) {13 ++count[c - '0'];14 counts.push_back(count);15 pows.push_back(pows.back() * kBase % kHash);16 hash.push_back((hash.back() * kBase + val(c)) % kHash);17 }18 19 for (int i = 0; i < s.length(); ++i)20 for (int j = i; j < s.length(); ++j)21 if (isSameFreq(counts, i, j))22 seen.insert(getRollingHash(i, j + 1, hash, pows));23 24 return seen.size();25 }26 27 private:28 static constexpr int kMax = 1001;29 static constexpr int kBase = 11;30 static constexpr int kHash = 1'000'000'007;31 32 static constexpr int val(char c) {33 return c - '0' + 1;34 }35 36 37 bool isSameFreq(const vector<vector<int>>& counts, int i, int j) {38 vector<int> count = counts[j];39 if (i > 0)40 for (int num = 0; num < 10; ++num)41 count[num] -= counts[i - 1][num];42 return equalFreq(count);43 }44 45 bool equalFreq(const vector<int>& count) {46 int minfreq = kMax;47 int maxfreq = 0;48 for (const int freq : count)49 if (freq > 0) {50 minfreq = min(minfreq, freq);51 maxfreq = max(maxfreq, freq);52 }53 return minfreq == maxfreq;54 }55 56 57 int getRollingHash(int l, int r, const vector<long>& hash,58 const vector<long>& pows) {59 const long h = (hash[r] - hash[l] * pows[r - l]) % kHash;60 return h < 0 ? h + kHash : h;61 }62};63