- 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
- 93 lines of Python from the credited upstream file count-the-number-of-ideal-arrays.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit 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.
123 4import collections5 6 78class Solution(object):9 def idealArrays(self, n, maxValue):10 """11 :type n: int12 :type maxValue: int13 :rtype: int14 """15 MOD = 10**9+716 fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]17 def nCr(n, k):18 while len(inv) <= n: 19 fact.append(fact[-1]*len(inv) % MOD)20 inv.append(inv[MOD%len(inv)]*(MOD-MODlen(inv)) % MOD) 21 inv_fact.append(inv_fact[-1]*inv[-1] % MOD)22 return (fact[n]*inv_fact[n-k] % MOD) * inv_fact[k] % MOD23 24 def linear_sieve_of_eratosthenes(n): 25 primes = []26 spf = [-1]*(n+1) 27 for i in xrange(2, n+1):28 if spf[i] == -1:29 spf[i] = i30 primes.append(i)31 for p in primes:32 if i*p > n or p > spf[i]:33 break34 spf[i*p] = p35 return primes36 37 def prime_factors(x):38 factors = collections.Counter()39 for p in primes:40 if p*p > x:41 break42 while x%p == 0:43 factors[p] += 144 x = p45 if x != 1:46 factors[x] += 147 return factors48 49 primes = linear_sieve_of_eratosthenes(int(maxValue**0.5))50 result = 051 for k in xrange(1, maxValue+1):52 total = 153 for c in prime_factors(k).itervalues():54 total = (total*nCr(n+c-1, c))%MOD 55 result = (result+total)%MOD56 return result57 58 596061import collections62 63 6465class Solution2(object):66 def idealArrays(self, n, maxValue):67 """68 :type n: int69 :type maxValue: int70 :rtype: int71 """72 MOD = 10**9+773 fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]74 def nCr(n, k):75 while len(inv) <= n: 76 fact.append(fact[-1]*len(inv) % MOD)77 inv.append(inv[MOD%len(inv)]*(MOD-MODlen(inv)) % MOD) 78 inv_fact.append(inv_fact[-1]*inv[-1] % MOD)79 return (fact[n]*inv_fact[n-k] % MOD) * inv_fact[k] % MOD80 81 result = 082 dp = collections.Counter(xrange(1, maxValue+1))83 for i in xrange(n): 84 new_dp = collections.Counter()85 total = 086 for x, c in dp.iteritems():87 total = (total+c)%MOD88 for y in xrange(x+x, maxValue+1, x): 89 new_dp[y] += c90 result = (result+total*nCr(n-1, i))%MOD91 dp = new_dp92 return result93