- 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
- 68 lines of Python from the credited upstream file good-subsequence-queries.py.
- The implementation visibly relies on sequence storage.
- No explicit 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.
1234 56def precompute(r):7 factors = [[] for _ in xrange(r+1)]8 curr, k = 1, 09 for i in xrange(2, len(factors)):10 if factors[i]:11 continue12 if curr*i <= r:13 curr *= i14 k += 115 for j in xrange(i, len(factors), i):16 factors[j].append(i)17 return factors, k18 19 20MAX_NUMS = 5000021FACTORS, K = precompute(MAX_NUMS)22class Solution(object):23 def countGoodSubseq(self, nums, p, queries):24 """25 :type nums: List[int]26 :type p: int27 :type queries: List[List[int]]28 :rtype: int29 """30 if len(nums) == 1:31 return 032 curr = [0]33 mx = max(max(nums), max(x for _, x in queries))34 cnt = [0]*(mx+1)35 cnt2 = [0]*(len(nums)+1)36 def update(x, d):37 if x%p:38 return39 for q in FACTORS[xp]:40 cnt2[cnt[q]] -= 141 cnt[q] += d42 cnt2[cnt[q]] += 143 curr[0] += d44 45 def check():46 if curr[0] == 0 or cnt2[curr[0]]:47 return False48 if curr[0] != len(nums) or len(nums) > K:49 return True50 for i in xrange(len(nums)):51 update(nums[i], -1)52 found = (cnt2[curr[0]] == 0)53 update(nums[i], +1)54 if found:55 return True56 return False57 58 result = 059 for x in nums:60 update(x, +1)61 for i, x in queries:62 update(nums[i], -1)63 nums[i] = x64 update(nums[i], +1)65 if check():66 result += 167 return result68