- 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
- 58 lines of Java from the credited upstream file 2954.java.
- The implementation visibly relies on sequence storage.
- 2 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 numberOfSequence(int n, int[] sick) {3 final long[][] factAndInvFact = getFactAndInvFact(n - sick.length);4 final long[] fact = factAndInvFact[0];5 final long[] invFact = factAndInvFact[1];6 long ans = fact[n - sick.length]; 7 int prevSick = -1;8 9 for (int i = 0; i < sick.length; ++i) {10 11 12 final int nonInfected = sick[i] - prevSick - 1;13 prevSick = sick[i];14 if (nonInfected == 0)15 continue;16 ans *= invFact[nonInfected];17 ans %= MOD;18 if (i > 0) {19 20 21 22 23 ans *= modPow(2, nonInfected - 1);24 ans %= MOD;25 }26 }27 28 final int nonInfected = n - sick[sick.length - 1] - 1;29 ans *= invFact[nonInfected];30 return (int) (ans % MOD);31 }32 33 private static final int MOD = 1_000_000_007;34 35 private long[][] getFactAndInvFact(int n) {36 long[] fact = new long[n + 1];37 long[] invFact = new long[n + 1];38 long[] inv = new long[n + 1];39 fact[0] = invFact[0] = 1;40 inv[0] = inv[1] = 1;41 for (int i = 1; i <= n; ++i) {42 if (i >= 2)43 inv[i] = MOD - MOD / i * inv[MOD % i] % MOD;44 fact[i] = fact[i - 1] * i % MOD;45 invFact[i] = invFact[i - 1] * inv[i] % MOD;46 }47 return new long[][] {fact, invFact};48 }49 50 private long modPow(long x, long n) {51 if (n == 0)52 return 1;53 if (n % 2 == 1)54 return x * modPow(x % MOD, (n - 1)) % MOD;55 return modPow(x * x % MOD, (n / 2)) % MOD;56 }57}58