# Program to find k-th largest XOR coordinate value in Python

PythonServer Side ProgrammingProgramming

Suppose we have one m x n matrix. and another value k. Here the value of coordinate (a, b) of the matrix is the XOR of all matrix[i, j] where i in range (0 to a) and j in range (0 to b). We have to find the kth largest value (1-indexed) of all the coordinates of matrix.

So, if the input is like

 5 2 1 6

And k = 1, then the output will be 7 because the value of coordinate (0,1) is 5 XOR 2 = 7, and this is the largest one

To solve this, we will follow these steps −

• m := row count, n := column count
• for i in range 0 to m - 1, do
• for j in range 0 to n - 1, do
• if j is non-zero, then
• matrix[i, j] := matrix[i, j] XOR matrix[i, j-1]
• seen := a new map
• count := 0
• for i in range 0 to n - 1, do
• for j in range 0 to m - 1, do
• if j is non-zero, then
• matrix[j, i] := matrix[j, i] XOR matrix[j-1, i]
• seen[matrix[j, i]] = (1+seen[matrix[j, i]] if possible, otherwise 1)
• count := count + 1
• if count > k, then
• min_value := minimum of seen
• seen[min_value] := seen[min_value] - 1
• if seen[min_value] is 0, then
• delete min_value-th element from seen
• return minimum of seen

## Example

Let us see the following implementation to get better understanding −

def solve(matrix, k):
m, n = len(matrix), len(matrix[0])
for i in range(m):
for j in range(n):
if j:
matrix[i][j] ^= matrix[i][j-1]

seen = {}
count = 0
for i in range(n):
for j in range(m):
if j:
matrix[j][i] ^= matrix[j-1][i]

seen[matrix[j][i]] = seen.get(matrix[j][i], 0) + 1
count += 1

if count > k:
min_value = min(seen)
seen[min_value] -= 1
if not seen[min_value]:
seen.pop(min_value)

return min(seen)
matrix = [[5,2],[1,6]]
k = 1
print(solve(matrix, k))

## Input

[[5,2],[1,6]], 1


## Output

7
Updated on 07-Oct-2021 11:19:54