- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 55 lines of Python from the credited upstream file number-of-distinct-subarrays-with-at-most-k-odd-integers.py.
- The implementation visibly relies on hash lookup.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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 distinctSubarraysWithAtMostKOddIntegers(self, A, K):10 def countDistinct(A, left, right, trie): 11 result = 012 for i in reversed(xrange(left, right+1)):13 if A[i] not in trie:14 result += 115 trie = trie[A[i]]16 return result17 18 _trie = lambda: collections.defaultdict(_trie)19 trie = _trie()20 result, left, count = 0, 0, 021 for right in xrange(len(A)):22 count += A[right]%223 while count > K:24 count -= A[left]%225 left += 126 result += countDistinct(A, left, right, trie)27 return result28 29 30313233class Solution2(object):34 def distinctSubarraysWithAtMostKOddIntegers(self, A, K):35 def countDistinct(A, left, right, trie): 36 result = 037 for i in xrange(left, right+1):38 if A[i] not in trie:39 result += 140 trie = trie[A[i]]41 return result42 43 _trie = lambda: collections.defaultdict(_trie)44 trie = _trie()45 result = 046 for left in xrange(len(A)):47 count = 048 for right in xrange(left, len(A)):49 count += A[right]%250 if count > K:51 right -= 152 break53 result += countDistinct(A, left, right, trie)54 return result55