Minimum XOR Path in a Grid

You are given an m x n integer grid. You start at the top-left (0, 0) and must travel to the bottom-right (m - 1, n - 1).

You can only move RIGHT or DOWN. The cost of your path is the bitwise XOR of all the numbers you step on.

Find the absolute minimum possible XOR cost among all valid paths.

Example 1:

Input: grid = [[1, 2], [3, 4]]

Output: 6

Explanation:

- Path 1: (0,0) -> (0,1) -> (1,1). XOR = 1 ^ 2 ^ 4 = 7.

- Path 2: (0,0) -> (1,0) -> (1,1). XOR = 1 ^ 3 ^ 4 = 6.

The minimum XOR value is 6.

Example 2:

Input: grid = [[6, 7], [5, 8]]

Output: 9

Explanation:

- Path 1: 6 ^ 7 ^ 8 = 9.

- Path 2: 6 ^ 5 ^ 8 = 11.

If you greedily picked the smaller XOR at the first step (6^5=3 is smaller than 6^7=1), you would end up with 11. By tracking ALL possibilities, you correctly find that the "worse" early path leads to the optimal 9.

Now Your Turn!

Pick the correct output for the given input

Input: grid = [[2, 7, 5]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= m == grid.length <= 1000
  • 1 <= n == grid[i].length <= 1000
  • m * n <= 1000
  • 0 <= grid[i][j] <= 1023​

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int minimumXORPath(vector<vector<int>>& grid) {
// Write your code here
}
};
Test Case

Input:

Grid