- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 66 lines of Java from the credited upstream file 2539.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 countGoodSubsequences(String s) {3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 final int MOD = 1_000_000_007;20 int ans = 0;21 int[] count = new int[26];22 23 for (final char c : s.toCharArray())24 ++count[c - 'a'];25 26 final int maxFreq = Arrays.stream(count).max().getAsInt();27 final long[][] factAndInvFact = getFactAndInvFact(maxFreq);28 final long[] fact = factAndInvFact[0];29 final long[] invFact = factAndInvFact[1];30 31 for (int freq = 1; freq <= maxFreq; ++freq) {32 long numSubseqs = 1; 33 for (final int charFreq : count)34 if (charFreq >= freq)35 numSubseqs = (numSubseqs + 36 numSubseqs * nCk(charFreq, freq, fact, invFact)) %37 MOD;38 ans += numSubseqs - 1; 39 ans %= MOD;40 }41 42 return ans;43 }44 45 private static final int MOD = 1_000_000_007;46 47 private long[][] getFactAndInvFact(int n) {48 long[] fact = new long[n + 1];49 long[] invFact = new long[n + 1];50 long[] inv = new long[n + 1];51 fact[0] = invFact[0] = 1;52 inv[0] = inv[1] = 1;53 for (int i = 1; i <= n; ++i) {54 if (i >= 2)55 inv[i] = MOD - MOD / i * inv[MOD % i] % MOD;56 fact[i] = fact[i - 1] * i % MOD;57 invFact[i] = invFact[i - 1] * inv[i] % MOD;58 }59 return new long[][] {fact, invFact};60 }61 62 private int nCk(int n, int k, long[] fact, long[] invFact) {63 return (int) (fact[n] * invFact[k] % MOD * invFact[n - k] % MOD);64 }65}66