#3882

Minimum XOR Path in a Grid

Medium
ArrayDynamic ProgrammingBit ManipulationMatrixDynamic ProgrammingGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^(m+n))
O(m * n * k)
Space
O(m+n)
O(m * n * k)
💡

Intuition

Time O(m * n * k)Space O(m * n * k)

Use dynamic programming to store possible XOR values at each cell, reducing redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array to track possible XOR values for each cell.
  2. 2Step 2: Iterate through the grid, updating the DP array based on previous cell values.
  3. 3Step 3: Return the minimum XOR value at the bottom-right cell.
solution.py13 lines
1def minXorPath(grid):
2    m, n = len(grid), len(grid[0])
3    dp = [[set() for _ in range(n)] for _ in range(m)]
4    dp[0][0].add(grid[0][0])
5    for i in range(m):
6        for j in range(n):
7            if i > 0:
8                for x in dp[i-1][j]:
9                    dp[i][j].add(x ^ grid[i][j])
10            if j > 0:
11                for x in dp[i][j-1]:
12                    dp[i][j].add(x ^ grid[i][j])
13    return min(dp[m-1][n-1])

Complexity note: k is the number of unique XOR values, leading to a manageable complexity.

  • 1XOR operation is cumulative and can be optimized using dynamic programming.
  • 2Tracking multiple XOR values allows for efficient path evaluation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.