- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 61 lines of Python from the credited upstream file number-of-alternating-xor-partitions.py.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def alternatingXOR(self, nums, target1, target2):7 """8 :type nums: List[int]9 :type target1: int10 :type target2: int11 :rtype: int12 """13 MOD = 10**9+714 vals = [0, target1, target1^target2, target2]15 dp = [0]*len(vals)16 dp[0] = 117 prefix = 018 for i in xrange(len(nums)-1):19 new_dp = dp[:]20 prefix ^= nums[i] 21 for j in xrange(len(vals)):22 if vals[j] != prefix:23 continue24 new_dp[j] = (new_dp[j]+dp[(j-1)%len(dp)])%MOD25 dp = new_dp26 prefix ^= nums[-1]27 result = 028 for i in xrange(len(vals)):29 if vals[i] != prefix:30 continue31 result = (result+dp[(i-1)%len(dp)])%MOD32 return result33 34 353637import collections38 39 4041class Solution2(object):42 def alternatingXOR(self, nums, target1, target2):43 """44 :type nums: List[int]45 :type target1: int46 :type target2: int47 :rtype: int48 """49 MOD = 10**9+750 cnt1 = collections.defaultdict(int)51 cnt2 = collections.defaultdict(int)52 cnt2[0] = 153 result = prefix = 054 for x in nums:55 prefix ^= x56 c1 = cnt2[prefix^target1]57 c2 = cnt1[prefix^target2]58 cnt1[prefix] = (cnt1[prefix]+c1)%MOD59 cnt2[prefix] = (cnt2[prefix]+c2)%MOD60 return (c1+c2)%MOD61