#3811

Number of Alternating XOR Partitions

Medium
ArrayHash TableDynamic ProgrammingBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using dynamic programming and prefix XORs allows us to efficiently compute the XOR of any subarray, reducing the problem to checking valid partitions in linear time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Compute prefix XORs for the array.
  2. 2Step 2: Use dynamic programming to count valid partitions based on the prefix XORs.
  3. 3Step 3: Check if the current prefix XOR matches target1 or target2 and update the count accordingly.
solution.py14 lines
1def countPartitions(nums, target1, target2):
2    MOD = 10**9 + 7
3    n = len(nums)
4    pref = [0] * (n + 1)
5    for i in range(n):
6        pref[i + 1] = pref[i] ^ nums[i]
7    dp = [0] * (n + 1)
8    dp[0] = 1
9    for i in range(1, n + 1):
10        if pref[i] == target1:
11            dp[i] = (dp[i] + dp[i - 1]) % MOD
12        if i > 1 and pref[i] == target2:
13            dp[i] = (dp[i] + dp[i - 2]) % MOD
14    return dp[n]

Complexity note: We compute prefix XORs in O(n) and use a DP array to track valid partitions, leading to O(n) overall complexity.

  • 1Use prefix XORs for efficient block XOR calculations.
  • 2Dynamic programming helps in counting valid partitions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.