- 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 Java from the credited upstream file 2168.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 int equalDigitFrequency(String s) {3 final int n = s.length();4 int[][] counts = new int[n][]; 5 int[] count = new int[10];6 long[] pows = new long[n + 1]; 7 8 9 long[] hash = new long[n + 1];10 Set<Integer> seen = new HashSet<>();11 12 pows[0] = 1;13 14 for (int i = 0; i < n; ++i) {15 ++count[s.charAt(i) - '0'];16 counts[i] = count.clone();17 pows[i + 1] = pows[i] * BASE % HASH;18 hash[i + 1] = (hash[i] * BASE + val(s.charAt(i))) % HASH;19 }20 21 for (int i = 0; i < n; ++i)22 for (int j = i; j < n; ++j)23 if (isSameFreq(counts, i, j))24 seen.add(getRollingHash(i, j + 1, hash, pows));25 26 return seen.size();27 }28 29 private static final int MAX = 1001;30 private static final int BASE = 11;31 private static final int HASH = 1_000_000_007;32 33 private static int val(char c) {34 return c - '0' + 1;35 }36 37 38 private boolean isSameFreq(int[][] counts, int i, int j) {39 int[] count = counts[j].clone();40 if (i > 0)41 for (int num = 0; num < 10; ++num)42 count[num] -= counts[i - 1][num];43 return equalFreq(count);44 }45 46 private boolean equalFreq(int[] count) {47 int minfreq = MAX;48 int maxfreq = 0;49 for (final int freq : count)50 if (freq > 0) {51 minfreq = Math.min(minfreq, freq);52 maxfreq = Math.max(maxfreq, freq);53 }54 return minfreq == maxfreq;55 }56 57 58 private int getRollingHash(int l, int r, long[] hash, long[] pows) {59 final long h = (hash[r] - hash[l] * pows[r - l]) % HASH;60 return (int) (h < 0 ? h + HASH : h);61 }62}63