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
XOR Coordinate Values: Matrix → Coordinate Values → Kth LargestInput Matrix5216Coordinate Values5742(0,0)(0,1)(1,0)(1,1)Sorted75421st2nd3rd4thFor k=2, answer is 5 (2nd largest coordinate value)
Understanding the Visualization
1
Input Matrix
2D matrix with coordinate-based XOR calculations
2
Calculate Values
XOR of all elements from (0,0) to each coordinate
3
Find Kth Largest
Sort coordinate values and return kth largest
Key Takeaway
🎯 Key Insight: Use 2D prefix XOR for O(1) coordinate lookups, then find kth largest efficiently
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