Count Paths With the Given XOR Value - Problem

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.

Input & Output

Example 1 — Basic 2x2 Grid
$ Input: grid = [[5,2],[1,6]], k = 1
Output: 1
💡 Note: There are two paths: 5→2→6 (XOR = 5⊕2⊕6 = 1) and 5→1→6 (XOR = 5⊕1⊕6 = 2). Only the first path has XOR equal to k=1.
Example 2 — No Valid Paths
$ Input: grid = [[1,2],[3,4]], k = 10
Output: 0
💡 Note: The two paths are: 1→2→4 (XOR = 1⊕2⊕4 = 7) and 1→3→4 (XOR = 1⊕3⊕4 = 6). Neither equals k=10.
Example 3 — Single Cell
$ Input: grid = [[7]], k = 7
Output: 1
💡 Note: Only one path exists containing just the single cell. XOR = 7, which equals k=7.

Constraints

  • 1 ≤ m, n ≤ 300
  • 0 ≤ grid[i][j] ≤ 15
  • 0 ≤ k ≤ 15

Visualization

Tap to expand
Count Paths With Given XOR Value: grid=[[5,2],[1,6]], k=15216STARTENDPath 1: 5→2→6, XOR = 5⊕2⊕6 = 1 ✓Path 2: 5→1→6, XOR = 5⊕1⊕6 = 2 ✗Result: 1 path has XOR = k = 1
Understanding the Visualization
1
Input Grid
2D grid with values, target XOR value k
2
Find Paths
Only move right or down, track XOR along path
3
Count Valid
Return count of paths where XOR equals k
Key Takeaway
🎯 Key Insight: Use dynamic programming to track path counts for each XOR value at every position
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen