Skip to main content

Minimum XOR Path in a Grid - Solution & Explanation

MediumArrayDynamic ProgrammingBit ManipulationMatrix4 min readAsked at: Google
Practice this problem

Problem Statement

You are given a 2D integer array grid of size m * n.

You start at the top-left cell (0, 0) and want to reach the bottom-right cell (m - 1, n - 1).

At each step, you may move either right or down.

The cost of a path is defined as the bitwise XOR of all the values in the cells along that path, including the start and end cells.

Return the minimum possible XOR value among all valid paths from (0, 0) to (m - 1, n - 1).

 

Example 1:

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

Output: 6

Explanation:

There are two valid paths:

  • (0, 0) → (0, 1) → (1, 1) with XOR: 1 XOR 2 XOR 4 = 7
  • (0, 0) → (1, 0) → (1, 1) with XOR: 1 XOR 3 XOR 4 = 6

The minimum XOR value among all valid paths is 6.

Example 2:

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

Output: 9

Explanation:

There are two valid paths:

  • (0, 0) → (0, 1) → (1, 1) with XOR: 6 XOR 7 XOR 8 = 9
  • (0, 0) → (1, 0) → (1, 1) with XOR: 6 XOR 5 XOR 8 = 11

The minimum XOR value among all valid paths is 9.

Example 3:

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

Output: 0

Explanation:

There is only one valid path:

  • (0, 0) → (0, 1) → (0, 2) with XOR: 2 XOR 7 XOR 5 = 0

The XOR value of this path is 0, which is the minimum possible.

 

Constraints:

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

Approach Overview

Problem Overview: Given a grid of integers, move from the top-left cell to the bottom-right cell while accumulating the XOR of all visited values. The goal is to minimize the final XOR value. Movement is typically restricted to right and down, which means every path has a fixed length but different XOR outcomes.

Approach 1: Brute Force DFS Enumeration (Exponential Time)

The most direct strategy is to enumerate every valid path from (0,0) to (m-1,n-1). During the DFS traversal, keep a running XOR of the values along the path. When you reach the destination, update the minimum XOR seen so far. This explores roughly 2^(m+n) paths in the worst case because each step branches into two directions. Time complexity is O(2^(m+n)) and space complexity is O(m+n) due to recursion depth. This approach works only for very small grids but helps verify correctness and understand the XOR accumulation.

Approach 2: Dynamic Programming with XOR State Sets (O(m * n * K))

A more structured method stores all reachable XOR values at each cell. Define dp[i][j] as the set of XOR values obtainable when reaching cell (i,j). For each previous state from (i-1,j) or (i,j-1), compute newXor = prevXor ^ grid[i][j] and insert it into the current set. This effectively tracks all possible XOR results along different paths. If the value range is bounded, the number of XOR states per cell remains manageable. Time complexity becomes roughly O(m * n * K), where K is the number of distinct XOR states, and space complexity is O(m * n * K). This approach is a natural extension of grid dynamic programming with bit manipulation.

Approach 3: Meet-in-the-Middle Path XOR (Optimized)

For larger grids, enumerating full paths becomes expensive. Instead, split the path length in half. Generate all partial paths from the start until the middle layer and store their XOR values in hash maps keyed by position. Then generate paths backward from the destination to the same middle layer and combine XOR results. The final XOR of a complete path equals leftXor ^ rightXor ^ grid[mid], so checking combinations allows you to track the minimum result efficiently. Each side enumerates about half the path depth, reducing complexity from exponential in m+n to roughly O(2^((m+n)/2)) time and space. This technique appears often in graph traversal problems where path enumeration is unavoidable.

Recommended for interviews: Start by explaining the brute force DFS to show how XOR accumulates along a path. Then transition to the state-based DP or meet-in-the-middle optimization. Interviewers usually expect you to recognize that enumerating full paths is exponential and reduce the search space using XOR state tracking or path splitting.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force DFS Path EnumerationO(2^(m+n))O(m+n)Useful for very small grids or validating logic during prototyping
DP with XOR State SetsO(m * n * K)O(m * n * K)General solution when XOR value range is limited and paths share many states
Meet-in-the-Middle Path XORO(2^((m+n)/2))O(2^((m+n)/2))Preferred when grid size is larger and full path enumeration is too expensive

Video Solution

Leetcode 3882 | Minimum XOR Path in a Grid | Leetcode biweekly contest 179 • CodeWithMeGuys • 345 views views

Watch 3 more video solutions →

Frequently Asked Questions

Is Minimum XOR Path in a Grid easy or hard?
The problem is generally considered medium difficulty. Computing XOR along a single path is straightforward, but minimizing the XOR across many possible paths requires careful state tracking or meet-in-the-middle optimization.
Minimum XOR Path in a Grid Python/Java solution
Python and Java implementations typically maintain a set of XOR states per cell or generate partial XOR paths using DFS. Python uses sets and dictionaries for fast lookups, while Java commonly uses HashSet or HashMap. Both approaches maintain time complexity around O(m * n * K) for DP-based solutions.
How to solve Minimum XOR Path in a Grid in O(n)?
An O(n) solution generally does not exist because the number of possible paths grows exponentially with grid dimensions. Practical solutions rely on dynamic programming over XOR states or meet-in-the-middle enumeration to reduce the exponential factor while still considering all valid paths.
What is the best approach for Minimum XOR Path in a Grid?
The most efficient strategy for larger grids is the meet-in-the-middle approach. It splits the path enumeration into two halves, computing XOR values from the start and from the destination separately, then combining them. This reduces the exponential search from O(2^(m+n)) to roughly O(2^((m+n)/2)) while still exploring all valid path XOR combinations.
Is Minimum XOR Path in a Grid asked at Google/Amazon/Meta?
XOR path and bit manipulation grid problems appear in interviews at large tech companies such as Google, Amazon, and Meta. Variants often test understanding of XOR properties, path enumeration, and optimization techniques like meet-in-the-middle or DP with state compression.
What data structure is used in Minimum XOR Path in a Grid?
Common implementations use hash sets or hash maps to store reachable XOR values for each grid position. DFS recursion stacks or iterative stacks handle traversal, while meet-in-the-middle solutions often store XOR states in maps keyed by grid coordinates.
What is the time complexity of Minimum XOR Path in a Grid?
Brute force DFS takes O(2^(m+n)) time because every right/down path is explored. A dynamic programming approach with XOR state tracking runs in about O(m * n * K), where K is the number of distinct XOR values per cell. The optimized meet-in-the-middle approach runs in roughly O(2^((m+n)/2)).

Ready to solve this problem?

Practice Minimum XOR Path in a Grid with our built-in code editor and test cases.

Practice on FleetCode