#1738

Find Kth Largest XOR Coordinate Value

Medium
ArrayDivide and ConquerBit ManipulationSortingHeap (Priority Queue)MatrixPrefix SumQuickselectPrefix SumBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n * (m + n))
O(m * n log(m * n))
Space
O(m * n)
O(m * n)
💡

Intuition

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

Using a prefix XOR array allows us to compute the XOR for any submatrix in constant time after an initial setup. This significantly reduces the time complexity.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a prefix XOR matrix where each cell (i, j) contains the XOR of all elements from (0, 0) to (i, j).
  2. 2Step 2: Iterate through the original matrix to fill the prefix XOR matrix.
  3. 3Step 3: Use the prefix XOR matrix to compute the XOR value for each coordinate (a, b) in constant time.
  4. 4Step 4: Store the XOR values in a list and sort it.
  5. 5Step 5: Return the k-th largest value from the sorted list.
solution.py15 lines
1def kthLargestValue(matrix, k):
2    m, n = len(matrix), len(matrix[0])
3    prefix_xor = [[0] * n for _ in range(m)]
4    for i in range(m):
5        for j in range(n):
6            prefix_xor[i][j] = matrix[i][j]
7            if i > 0:
8                prefix_xor[i][j] ^= prefix_xor[i - 1][j]
9            if j > 0:
10                prefix_xor[i][j] ^= prefix_xor[i][j - 1]
11            if i > 0 and j > 0:
12                prefix_xor[i][j] ^= prefix_xor[i - 1][j - 1]
13    xor_values = [prefix_xor[i][j] for i in range(m) for j in range(n)]
14    xor_values.sort(reverse=True)
15    return xor_values[k - 1]

Complexity note: The time complexity is dominated by the sorting step after calculating the prefix XOR values, which is O(m * n log(m * n)).

  • 1Using prefix XOR allows for efficient submatrix XOR calculations.
  • 2Sorting the results helps in easily retrieving the k-th largest value.

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