Find Kth Largest XOR Coordinate Value Problem
Description
LeetCode Problem 1738.
You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k.
The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed).
Find the k^th largest value (1-indexed) of all the coordinates of matrix.
Example 1:
Input: matrix = [[5,2],[1,6]], k = 1
Output: 7
Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.
Example 2:
Input: matrix = [[5,2],[1,6]], k = 2
Output: 5
Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.
Example 3:
Input: matrix = [[5,2],[1,6]], k = 3
Output: 4
Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10000 <= matrix[i][j] <= 10^61 <= k <= m * n
Solution
Approach: 2D Prefix XOR, Then Pick the K-th Largest
Let s[i][j] be the XOR of all values in the rectangle with corners (0, 0) and (i - 1, j - 1). It is built from its neighbours the same way a 2D prefix sum is, except that XOR is its own inverse, so the overlap cancels out:
s[i][j] = s[i-1][j] ^ s[i][j-1] ^ s[i-1][j-1] ^ matrix[i-1][j-1]
Compute this for every cell and collect the m * n values. The answer is the k-th largest of them: sort in descending order, or use a heap or quickselect to avoid a full sort.
Complexity: O(mn log(mn)) time with sorting (O(mn) with quickselect) and O(mn) extra space.
from heapq import nlargest
class Solution:
def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:
m, n = len(matrix), len(matrix[0])
s = [[0] * (n + 1) for _ in range(m + 1)]
ans = []
for i in range(m):
for j in range(n):
s[i + 1][j + 1] = s[i + 1][j] ^ s[i][j + 1] ^ s[i][j] ^ matrix[i][j]
ans.append(s[i + 1][j + 1])
return nlargest(k, ans)[-1]