- 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
- 58 lines of C++ from the credited upstream file number-of-alternating-xor-partitions.cpp.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- 4 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 {6public:7 int alternatingXOR(vector<int>& nums, int target1, int target2) {8 static const int MOD = 1e9 + 7;9 10 vector<int> vals = {0, target1, target1 ^ target2, target2};11 vector<int> dp(size(vals));12 dp[0] = 1;13 int prefix = 0;14 for (int i = 0; i + 1 < size(nums); ++i) {15 vector<int> new_dp(dp);16 prefix ^= nums[i];17 for (int j = 0; j < size(vals); ++j) {18 if (vals[j] != prefix) {19 continue;20 }21 new_dp[j] = (new_dp[j] + dp[((j - 1) % size(dp) + size(dp)) % size(dp)]) % MOD;22 }23 dp = move(new_dp);24 }25 prefix ^= nums.back();26 int result = 0;27 for (int j = 0; j < size(vals); ++j) {28 if (vals[j] != prefix) {29 continue;30 }31 result = (result + dp[((j - 1) % size(dp) + size(dp)) % size(dp)]) % MOD;32 }33 return result;34 }35};36 37383940class Solution2 {41public:42 int alternatingXOR(vector<int>& nums, int target1, int target2) {43 static const int MOD = 1e9 + 7;44 45 unordered_map<int, int> cnt1, cnt2;46 cnt2[0] = 1;47 int c1 = 0, c2 = 0;48 for (int i = 0, prefix = 0; i < size(nums); ++i) {49 prefix ^= nums[i];50 c1 = cnt2[prefix ^ target1];51 c2 = cnt1[prefix ^ target2];52 cnt1[prefix] = (cnt1[prefix] + c1) % MOD;53 cnt2[prefix] = (cnt2[prefix] + c2) % MOD;54 }55 return (c1 + c2) % MOD;56 }57};58