LeetCode #3393 — MEDIUM

Count Paths With the Given XOR Value

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

Solve on LeetCode
The Problem

Problem Statement

You are given a 2D integer array grid with size m x n. You are also given an integer k.

Your task is to calculate the number of paths you can take from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1) satisfying the following constraints:

  • You can either move to the right or down. Formally, from the cell (i, j) you may move to the cell (i, j + 1) or to the cell (i + 1, j) if the target cell exists.
  • The XOR of all the numbers on the path must be equal to k.

Return the total number of such paths.

Since the answer can be very large, return the result modulo 109 + 7.

Example 1:

Input: grid = [[2, 1, 5], [7, 10, 0], [12, 6, 4]], k = 11

Output: 3

Explanation: 

The 3 paths are:

  • (0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2)
  • (0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2)
  • (0, 0) → (0, 1) → (1, 1) → (2, 1) → (2, 2)

Example 2:

Input: grid = [[1, 3, 3, 3], [0, 3, 3, 2], [3, 0, 1, 1]], k = 2

Output: 5

Explanation:

The 5 paths are:

  • (0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2) → (2, 3)
  • (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2) → (2, 3)
  • (0, 0) → (1, 0) → (1, 1) → (1, 2) → (1, 3) → (2, 3)
  • (0, 0) → (0, 1) → (1, 1) → (1, 2) → (2, 2) → (2, 3)
  • (0, 0) → (0, 1) → (0, 2) → (1, 2) → (2, 2) → (2, 3)

Example 3:

Input: grid = [[1, 1, 1, 2], [3, 0, 3, 2], [3, 0, 2, 2]], k = 10

Output: 0

Constraints:

  • 1 <= m == grid.length <= 300
  • 1 <= n == grid[r].length <= 300
  • 0 <= grid[r][c] < 16
  • 0 <= k < 16
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 a 2D integer array grid with size m x n. You are also given an integer k. Your task is to calculate the number of paths you can take from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1) satisfying the following constraints: You can either move to the right or down. Formally, from the cell (i, j) you may move to the cell (i, j + 1) or to the cell (i + 1, j) if the target cell exists. The XOR of all the numbers on the path must be equal to k. Return the total number of such paths. Since the answer can be very large, return the result modulo 109 + 7.

Baseline thinking

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

Pattern signal: Array · Dynamic Programming · Bit Manipulation

Example 1

[[2,1,5],[7,10,0],[12,6,4]]
11

Example 2

[[1,3,3,3],[0,3,3,2],[3,0,1,1]]
2

Example 3

[[1,1,1,2],[3,0,3,2],[3,0,2,2]]
10

Related Problems

  • Count Pairs With XOR in a Range (count-pairs-with-xor-in-a-range)
Step 02

Core Insight

What unlocks the optimal approach

  • Use DP.
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 #3393: Count Paths With the Given XOR Value
class Solution {
  public int countPathsWithXorValue(int[][] grid, int k) {
    final int MAX = 15;
    final int m = grid.length;
    final int n = grid[0].length;
    Integer[][][] mem = new Integer[m][n][MAX + 1];
    return count(grid, 0, 0, 0, k, mem);
  }

  private static final int MOD = 1_000_000_007;

  // Return the number of paths from (i, j) to (m - 1, n - 1) with XOR value
  // `xors`.
  private int count(int[][] grid, int i, int j, int xors, int k, Integer[][][] mem) {
    if (i == grid.length || j == grid[0].length)
      return 0;
    xors ^= grid[i][j];
    if (i == grid.length - 1 && j == grid[0].length - 1)
      return xors == k ? 1 : 0;
    if (mem[i][j][xors] != null)
      return mem[i][j][xors];
    final int right = count(grid, i, j + 1, xors, k, mem) % MOD;
    final int down = count(grid, i + 1, j, xors, k, mem) % MOD;
    return mem[i][j][xors] = (right + down) % MOD;
  }
}
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 × m)
Space
O(n × m)

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.

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.