LeetCode #3811 — MEDIUM

Number of Alternating XOR Partitions

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer array nums and two distinct integers target1 and target2.

A partition of nums splits it into one or more contiguous, non-empty blocks that cover the entire array without overlap.

A partition is valid if the bitwise XOR of elements in its blocks alternates between target1 and target2, starting with target1.

Formally, for blocks b1, b2, …:

  • XOR(b1) = target1
  • XOR(b2) = target2 (if it exists)
  • XOR(b3) = target1, and so on.

Return the number of valid partitions of nums, modulo 109 + 7.

Note: A single block is valid if its XOR equals target1.

Example 1:

Input: nums = [2,3,1,4], target1 = 1, target2 = 5

Output: 1

Explanation:​​​​​​​

  • The XOR of [2, 3] is 1, which matches target1.
  • The XOR of the remaining block [1, 4] is 5, which matches target2.
  • This is the only valid alternating partition, so the answer is 1.

Example 2:

Input: nums = [1,0,0], target1 = 1, target2 = 0

Output: 3

Explanation:

  • ​​​​​​​The XOR of [1, 0, 0] is 1, which matches target1.
  • The XOR of [1] and [0, 0] are 1 and 0, matching target1 and target2.
  • The XOR of [1, 0] and [0] are 1 and 0, matching target1 and target2.
  • Thus, the answer is 3.​​​​​​​

Example 3:

Input: nums = [7], target1 = 1, target2 = 7

Output: 0

Explanation:

  • The XOR of [7] is 7, which does not match target1, so no valid partition exists.

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i], target1, target2 <= 105
  • target1 != target2
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums and two distinct integers target1 and target2. A partition of nums splits it into one or more contiguous, non-empty blocks that cover the entire array without overlap. A partition is valid if the bitwise XOR of elements in its blocks alternates between target1 and target2, starting with target1. Formally, for blocks b1, b2, …: XOR(b1) = target1 XOR(b2) = target2 (if it exists) XOR(b3) = target1, and so on. Return the number of valid partitions of nums, modulo 109 + 7. Note: A single block is valid if its XOR equals target1.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Hash Map · Dynamic Programming · Bit Manipulation

Example 1

[2,3,1,4]
1
5

Example 2

[1,0,0]
1
0

Example 3

[7]
1
7
Step 02

Core Insight

What unlocks the optimal approach

  • Use dynamic programming.
  • Compute prefix XORs so the XOR of a block <code>[l..r]</code> can be obtained as <code>pref[r] ^ pref[l - 1]</code>.
  • For each position, try ending a block whose XOR equals the expected target, and transition to the next state (alternating between <code>target1</code> and <code>target2</code>).
  • Use a hash map or array indexed by prefix XOR values to efficiently count valid previous split points.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3811: Number of Alternating XOR Partitions
class Solution {
    public int alternatingXOR(int[] nums, int target1, int target2) {
        final int mod = (int) 1e9 + 7;

        Map<Integer, Integer> cnt1 = new HashMap<>();
        Map<Integer, Integer> cnt2 = new HashMap<>();
        cnt2.put(0, 1);

        int ans = 0;
        int pre = 0;
        for (int x : nums) {
            pre ^= x;
            int a = cnt2.getOrDefault(pre ^ target1, 0);
            int b = cnt1.getOrDefault(pre ^ target2, 0);
            ans = (a + b) % mod;
            cnt1.put(pre, (cnt1.getOrDefault(pre, 0) + a) % mod);
            cnt2.put(pre, (cnt2.getOrDefault(pre, 0) + b) % mod);
        }

        return ans;
    }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(n)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Mutating counts without cleanup

Wrong move: Zero-count keys stay in map and break distinct/count constraints.

Usually fails on: Window/map size checks are consistently off by one.

Fix: Delete keys when count reaches zero.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.