Find Kth Largest XOR Coordinate Value — LeetCode 1738 Python Solution

MediumBit ManipulationArrayDivide and ConquerMatrixPrefix SumQuickselectSortingHeap (Priority Queue)
Problem
#1738
Pattern
Prefix Sum
Reading time
2 min

The problem

You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k.

Example

Input
matrix = [[5,2],[1,6]], k = 1
Output
7
Explanation
The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.

Python solution

Python
class Solution:
    def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:
        m, n = len(matrix), len(matrix[0])
        s = [[0] * (n + 1) for _ in range(m + 1)]
        ans = []
        for i in range(m):
            for j in range(n):
                s[i + 1][j + 1] = s[i + 1][j] ^ s[i][j + 1] ^ s[i][j] ^ matrix[i][j]
                ans.append(s[i + 1][j + 1])
        return nlargest(k, ans)[-1]

Complexity

MeasureComplexity
TimeO(m \times n \times \log (m \times n)) or O(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1738. Find Kth Largest XOR Coordinate Value is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1738. Find Kth Largest XOR Coordinate Value?
LeetCode 1738. Find Kth Largest XOR Coordinate Value is rated Medium on LeetCode.
What topics does LeetCode 1738. Find Kth Largest XOR Coordinate Value cover?
LeetCode 1738. Find Kth Largest XOR Coordinate Value is tagged Bit Manipulation, Array, Divide and Conquer, Matrix, Prefix Sum, Quickselect, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview