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 XOR Value INPUT 2x2 Grid: 5 (0,0) 2 (0,1) 1 (1,0) 6 (1,1) S E Target XOR (k): k = 1 Two possible paths: Path 1: Right then Down Path 2: Down then Right Moves: Right or Down only ALGORITHM STEPS 1 Define DP State dp[i][j][x] = paths to (i,j) with XOR value x 2 Initialize Base dp[0][0][grid[0][0]] = 1 dp[0][0][5] = 1 3 Fill DP Table For each cell, combine from top/left with XOR 4 Return Answer dp[m-1][n-1][k] dp[1][1][1] = result Path XOR Calculations: Path 1: 5-->2-->6 5 XOR 2 = 7 7 XOR 6 = 1 [OK] Path 2: 5-->1-->6 5 XOR 1 = 4 4 XOR 6 = 2 [NO] FINAL RESULT Valid Path Found: 5 2 1 6 XOR Chain: 5 XOR 2 XOR 6 = 1 = k (Target Met!) Output: 1 1 valid path found (mod 10^9 + 7) Key Insight: Use 3D DP where dp[i][j][x] tracks paths to cell (i,j) with cumulative XOR value x. XOR property: A XOR B XOR B = A, making state transitions efficient. Time: O(m * n * maxXOR), Space: O(m * n * maxXOR) where maxXOR depends on grid values. TutorialsPoint - Count Paths With the Given XOR Value | Dynamic Programming Approach
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