Magicsheet logo

Count Paths With the Given XOR Value

Medium
37.5%
Updated 8/1/2025

Count Paths With the Given XOR Value

What is this problem about?

The "Count Paths With the Given XOR Value interview question" is a matrix traversal problem. You are given an mimesnm imes n grid of integers and a target value k. You can only move down or right from the top-left cell (0,0)(0, 0) to the bottom-right cell (m1,n1)(m-1, n-1). You need to find the number of distinct paths whose XOR sum of elements is exactly equal to k.

Why is this asked in interviews?

Microsoft uses the "Count Paths With the Given XOR Value coding problem" to evaluate a candidate's proficiency in Dynamic Programming. It’s a variation of the standard "path counting" problem but requires an extra dimension in the DP table to track the XOR sum. It tests your ability to handle bitwise state transitions and manage modulo-based counting.

Algorithmic pattern used

This problem is solved using 3D Dynamic Programming.

  1. DP State: dp[i][j][current_xor] represents the number of paths from (0,0)(0, 0) to (i,j)(i, j) that result in a cumulative XOR sum of current_xor.
  2. Transition:
    • From top: dp[i][j][current_xor ^ grid[i][j]] += dp[i-1][j][current_xor]
    • From left: dp[i][j][current_xor ^ grid[i][j]] += dp[i][j-1][current_xor]
  3. Base Case: dp[0][0][grid[0][0]] = 1.
  4. Complexity: The XOR sum can range from 0 to 15 (if grid values are small) or higher. The time complexity is O(MimesNimesextMaxXOR)O(M imes N imes ext{MaxXOR}).

Example explanation

Grid: [[1, 2], [3, 4]], k=6k = 6

  • Path 1: (1 -> 2 -> 4). XOR = 124=71 \oplus 2 \oplus 4 = 7.
  • Path 2: (1 -> 3 -> 4). XOR = 134=61 \oplus 3 \oplus 4 = 6.
  • Only Path 2 matches kk. Result: 1.

Common mistakes candidates make

  • Memory Management: Using a massive 3D array when the grid or values are large. You can optimize space to 2D (current and previous rows) since each cell only depends on the cell above and to the left.
  • Recursive TLE: Attempting a simple recursion without memoization, which leads to exponential time complexity (O(2M+N)O(2^{M+N})).
  • Initialization: Forgetting to handle the boundaries (first row and first column) correctly.

Interview preparation tip

When adding a condition (like XOR sum or sum) to a path problem, the condition usually becomes the third dimension of your DP table. Practice "State Space" analysis to determine how large your DP table needs to be.

Similar Questions