Find Kth Largest XOR Coordinate Value - Problem
You are given a 2D matrix of size
The coordinate value at position
For example, if we have a 3x3 matrix, there are 9 coordinate values (one for each position), and you need to find the kth largest among these values.
Goal: Return the kth largest coordinate value (1-indexed) among all possible coordinate positions in the matrix.
m x n containing non-negative integers, along with an integer k. Your task is to find the kth largest XOR coordinate value in the matrix.The coordinate value at position
(a, b) is defined as the XOR of all elements in the submatrix from (0, 0) to (a, b) inclusive. In other words, it's the XOR of all matrix[i][j] where 0 ≤ i ≤ a and 0 ≤ j ≤ b.For example, if we have a 3x3 matrix, there are 9 coordinate values (one for each position), and you need to find the kth largest among these values.
Goal: Return the kth largest coordinate value (1-indexed) among all possible coordinate positions in the matrix.
Input & Output
example_1.py — Basic Example
$
Input:
matrix = [[5,2],[1,6]], k = 1
›
Output:
7
💡 Note:
Coordinate values are: (0,0)=5, (0,1)=5⊕2=7, (1,0)=5⊕1=4, (1,1)=5⊕2⊕1⊕6=2. The largest value is 7.
example_2.py — Larger Matrix
$
Input:
matrix = [[5,2,3],[1,4,6]], k = 3
›
Output:
4
💡 Note:
All coordinate values: [5,7,4,4,2,0]. Sorted descending: [7,5,4,4,2,0]. The 3rd largest is 4.
example_3.py — Single Element
$
Input:
matrix = [[10]], k = 1
›
Output:
10
💡 Note:
Only one coordinate (0,0) with value 10, so the 1st largest is 10.
Visualization
Tap to expand
Understanding the Visualization
1
Understand the Problem
Each coordinate (a,b) has a value = XOR of all elements from (0,0) to (a,b)
2
Build Prefix XOR
Use 2D prefix XOR where prefixXor[i][j] = XOR of all elements from (0,0) to (i,j)
3
Apply XOR Properties
Use formula: prefixXor[i][j] = matrix[i][j] ⊕ prefixXor[i-1][j] ⊕ prefixXor[i][j-1] ⊕ prefixXor[i-1][j-1]
4
Track K Largest
Use min heap to efficiently maintain only the k largest coordinate values
5
Return Result
The top of the min heap is the kth largest value
Key Takeaway
🎯 Key Insight: XOR prefix sums combined with min heap optimization gives us the most efficient solution, especially when k is much smaller than the total number of coordinates.
Time & Space Complexity
Time Complexity
O(mn log k)
O(mn) to build prefix XOR matrix, O(log k) for each heap operation, total O(mn log k)
⚡ Linearithmic
Space Complexity
O(mn + k)
O(mn) for prefix XOR matrix, O(k) for the min heap
⚡ Linearithmic Space
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 1000
- 0 ≤ matrix[i][j] ≤ 106
- 1 ≤ k ≤ m * n
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code