- 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
- 68 lines of Java from the credited upstream file 1735.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 8 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[] waysToFillArray(int[][] queries) {3 final int MAX = 10_000;4 final int MAX_FREQ = 13; 5 final int[] minPrimeFactors = sieveEratosthenes(MAX + 1);6 final long[][] factAndInvFact = getFactAndInvFact(MAX + MAX_FREQ - 1);7 final long[] fact = factAndInvFact[0];8 final long[] invFact = factAndInvFact[1];9 int[] ans = new int[queries.length];10 11 for (int i = 0; i < queries.length; ++i) {12 final int n = queries[i][0];13 final int k = queries[i][1];14 int res = 1;15 for (final int freq : getPrimeFactorsCount(k, minPrimeFactors).values())16 res = (int) ((long) res * nCk(n - 1 + freq, freq, fact, invFact) % MOD);17 ans[i] = res;18 }19 20 return ans;21 }22 23 private static final int MOD = 1_000_000_007;24 25 26 private int[] sieveEratosthenes(int n) {27 int[] minPrimeFactors = new int[n + 1];28 for (int i = 2; i <= n; ++i)29 minPrimeFactors[i] = i;30 for (int i = 2; i * i < n; ++i)31 if (minPrimeFactors[i] == i) 32 for (int j = i * i; j < n; j += i)33 minPrimeFactors[j] = Math.min(minPrimeFactors[j], i);34 return minPrimeFactors;35 }36 37 private Map<Integer, Integer> getPrimeFactorsCount(int num, int[] minPrimeFactors) {38 Map<Integer, Integer> count = new HashMap<>();39 while (num > 1) {40 final int divisor = minPrimeFactors[num];41 while (num % divisor == 0) {42 num /= divisor;43 count.put(divisor, count.merge(divisor, 1, Integer::sum));44 }45 }46 return count;47 }48 49 private long[][] getFactAndInvFact(int n) {50 long[] fact = new long[n + 1];51 long[] invFact = new long[n + 1];52 long[] inv = new long[n + 1];53 fact[0] = invFact[0] = 1;54 inv[0] = inv[1] = 1;55 for (int i = 1; i <= n; ++i) {56 if (i >= 2)57 inv[i] = MOD - MOD / i * inv[MOD % i] % MOD;58 fact[i] = fact[i - 1] * i % MOD;59 invFact[i] = invFact[i - 1] * inv[i] % MOD;60 }61 return new long[][] {fact, invFact};62 }63 64 private int nCk(int n, int k, long[] fact, long[] invFact) {65 return (int) (fact[n] * invFact[k] % MOD * invFact[n - k] % MOD);66 }67}68