VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-submatrix-with-kth-maximum-xor/

⇱ Smallest submatrix with Kth maximum XOR - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest submatrix with Kth maximum XOR

Last Updated : 15 Jul, 2025

Given a matrix m[][] of dimensions N × M and an integer K, calculate XOR(i, j) which is equal to the Bitwise Xor of all elements of submatrix from indices (1, 1) to (i, j)), for every index of the matrix. The task is to find the submatrix {(1, 1), ..., (i, j)} having Kth maximum XOR(i, j) value. If multiple such submatrices exist, then print the smallest one. 

Note: Consider the starting index of the matrix from (1, 1).

Examples:

Input: m[][] = {{1, 2}, {2, 3}}, K = 2
Output: 1 2
Explanation:
XOR(1, 1) : m[1][1] = 1
XOR(1, 2): m[1][1] xor m[1][2] = 3
XOR(2, 1): m[1][1] xor m[2][1] = 3
XOR(2, 2): m[1][1] xor m[1][2] xor m[2][1] xor m[2][2] = 2
Hence, the 2nd maximum value is 3 at position [1, 2].

Input: m[][] = {{1, 2, 3}, {2, 2, 1}, {2, 4, 2} }, k = 1
Output: 3 2

Approach: The idea is to find XOR (i, j) using Dynamic Programming.

  • Calculate the bitwise XOR(i, j) as xor[i][j] = xor[i-1][j] ^ xor[i][j-1] ^ xor[i-1][j-1] ^ m[i][j].
  • Store the XOR(i, j) values obtained for respective indices (i, j) in a Map.
  • Find the Kth maximum of all XOR(i, j) values using a Min-heap of size K.
  • Find the smallest index (i, j) for which XOR(i, j) is equal to the Kth maximum obtained in the above step using the Map.

Below is the implementation of the above approach:


Output: 
3 2

 

Time Complexity: O(N * M * log K)
Auxiliary Space: O(N * M)


 

Comment