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 kth largest value (1-indexed) of all the coordinates of matrix.

Input & Output

Example 1 — Basic 2x2 Matrix
$ Input: matrix = [[5,2],[1,6]], k = 1
Output: 7
💡 Note: Coordinate values: (0,0)=5, (0,1)=5⊕2=7, (1,0)=5⊕1=4, (1,1)=5⊕2⊕1⊕6=2. Sorted: [7,5,4,2]. 1st largest is 7.
Example 2 — Same Matrix, Different k
$ Input: matrix = [[5,2],[1,6]], k = 2
Output: 5
💡 Note: Same coordinate values [7,5,4,2]. 2nd largest is 5.
Example 3 — Single Row Matrix
$ Input: matrix = [[1,0,3,2]], k = 3
Output: 2
💡 Note: Coordinate values: (0,0)=1, (0,1)=1⊕0=1, (0,2)=1⊕0⊕3=2, (0,3)=1⊕0⊕3⊕2=0. Sorted: [2,1,1,0]. 3rd largest is 1.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 1000
  • 0 ≤ matrix[i][j] ≤ 106
  • 1 ≤ k ≤ m * n

Visualization

Tap to expand
Find Kth Largest XOR Coordinate Value INPUT 2D Matrix (2x2) 5 2 1 6 j=0 j=1 i=0 i=1 Parameters: matrix = [[5,2],[1,6]] k = 1 (find 1st largest) XOR of all elements from (0,0) to (a,b) inclusive value(a,b) = XOR(matrix[0..a][0..b]) ALGORITHM STEPS 1 Create XOR prefix matrix Build 2D prefix XOR array 2 Compute each coordinate XOR[i][j] using DP formula 3 Collect all XOR values Store in list for sorting 4 Find kth largest Sort desc, return k-1 index XOR Prefix Values: 5 7 4 0 5 5^2=7 5^1=4 5^2^1^6=0 Values: [5, 7, 4, 0] Sorted: [7, 5, 4, 0] k=1 --> index 0 --> 7 FINAL RESULT All XOR Coordinate Values: 5 7 4 0 1st largest Sorted (descending): 7 5 4 0 k=1 k=2 k=3 k=4 OUTPUT 7 [ OK ] 1st largest XOR value Key Insight: Use 2D prefix XOR with DP formula: XOR[i][j] = matrix[i][j] ^ XOR[i-1][j] ^ XOR[i][j-1] ^ XOR[i-1][j-1] This allows O(m*n) computation of all coordinate values. Then use sorting or heap for kth largest. Time: O(m*n*log(m*n)) | Space: O(m*n) TutorialsPoint - Find Kth Largest XOR Coordinate Value | Optimal Solution (2D Prefix XOR + Sorting)
Asked in
Google 35 Facebook 28 Microsoft 22
28.0K Views
Medium Frequency
~15 min Avg. Time
854 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen