C++ 1738.cpp
class Solution {
public:
int kthLargestValue(vector<vector<int>>& matrix, int k) {
auto exclusive = matrix;
// upper and left border
for (auto y = 1; y < exclusive.size(); y++)
exclusive[y][0] ^= exclusive[y - 1][0];
for (auto x = 1; x < exclusive[0].size(); x++)
exclusive[0][x] ^= exclusive[0][x - 1];
std::vector<int> all;
for (auto y = 0; y < exclusive.size(); y++)
for (auto x = 0; x < exclusive[y].size(); x++)
{
if (x > 0 && y > 0)
// the hardest part of this problem was figuring out the third term ...
exclusive[y][x] ^= exclusive[y - 1][x] ^ exclusive[y][x - 1] ^ exclusive[y - 1][x - 1];
all.push_back(exclusive[y][x]);
}
auto smallest = all.size() - k;
// partial sort
nth_element(all.begin(), all.begin() + smallest, all.end());
return all[smallest];
}
};
Difficulty
and has an acceptance rate of about 64% (40k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Divide And Conquer
- Heap (Priority Queue)
- Matrix
- Prefix Sum
- Quickselect
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The kthLargestValue method computes the k-th largest value among all possible XOR-accumulated sub-matrices of the input matrix. It first transforms the original matrix into a prefix-XOR representation, then gathers every cell’s prefix value into a flat container, and finally extracts the required order statistic using a partial selection algorithm.
Key Steps
Copy and Prepare Matrix
The algorithm begins by creating a mutable copy of the input matrix. This copy, named exclusive, will hold the intermediate prefix-XOR values while preserving the original data.
auto exclusive = matrix;
Compute Prefix XOR for the First Column
A forward pass over the first column accumulates XOR values vertically. Each cell in the first column becomes the XOR of itself and the cell directly above it, establishing the vertical component of the prefix.
for (auto y = 1; y < exclusive.size(); y++)
exclusive[y][0] ^= exclusive[y - 1][0];
Compute Prefix XOR for the First Row
A similar forward pass over the first row accumulates XOR values horizontally. Each cell in the first row becomes the XOR of itself and the cell to its left, establishing the horizontal component of the prefix.
for (auto x = 1; x < exclusive[0].size(); x++)
exclusive[0][x] ^= exclusive[0][x - 1];
Compute Full Prefix XOR and Collect Values
Two nested loops iterate over every cell. For interior cells (both row and column indices greater than zero) the algorithm combines four previously computed prefix values to obtain the current cell’s full prefix XOR. The expression
exclusive[y][x] ^= exclusive[y - 1][x] ^ exclusive[y][x - 1] ^ exclusive[y - 1][x - 1];
realizes the inclusion-exclusion principle for XOR, ensuring that each sub-matrix’s cumulative XOR is correctly represented. After updating a cell, its value is appended to the linear container all.
std::vector<int> all;
for (auto y = 0; y < exclusive.size(); y++)
for (auto x = 0; x < exclusive[y].size(); x++)
{
if (x > 0 && y > 0)
exclusive[y][x] ^= exclusive[y - 1][x] ^ exclusive[y][x - 1] ^ exclusive[y - 1][x - 1];
all.push_back(exclusive[y][x]);
}
Select the k-th Largest Value
The target index for the k-th largest element is computed as all.size() - k, converting the problem into a “k-th smallest” selection on the zero-based array. The standard library’s nth_element algorithm rearranges the container so that the element at the target position is exactly the one that would appear there in a fully sorted array, while the elements before it are not greater and those after it are not smaller. The method then returns the element at the computed position.
auto smallest = all.size() - k;
nth_element(all.begin(), all.begin() + smallest, all.end());
return all[smallest];
Edge Cases Handled
When the matrix consists of a single row, the first column loop does not execute, and the first row loop processes the entire row, correctly building the prefix XOR across the row. Conversely, for a single column matrix, the first row loop is bypassed, and the first column loop builds the vertical prefix. The nested collection loop works uniformly for both dimensions, ensuring that every cell’s prefix value is captured regardless of matrix shape.
If k equals the total number of sub-matrices, the computed index all.size() - k becomes zero, and nth_element positions the smallest element at the front of the container, which is then returned. When k is one, the index points to the last element, and nth_element places the largest value at that position, delivering the maximum XOR value.
The algorithm also gracefully handles matrices where all entries are identical. The XOR accumulation will produce predictable patterns, and the selection step still yields the correct order statistic without special-case logic.
Performance Optimizations
The implementation reuses the exclusive matrix for in-place prefix computation, avoiding the allocation of an additional auxiliary matrix. By updating each cell directly, memory traffic is minimized and cache locality is improved, especially during the sequential row-wise traversal.
The use of nth_element instead of a full sort reduces the amount of work required to locate the k-th largest value. nth_element performs a linear-time selection on average, rearranging only the necessary portion of the data to guarantee that the element at the target index is correctly positioned. This choice eliminates the overhead of sorting the entire all vector, which could be substantial for large matrices.
Collecting all prefix values into a contiguous std::vector<int> enables efficient bulk operations and leverages the standard library’s highly tuned algorithms. The contiguous layout also benefits from prefetching and reduces pointer indirection during the selection phase.
ELI5 - Simplified Explanation
Imagine a giant grid filled with blocks, where each block has a special number hidden inside. To play this game, we want to combine these numbers in a clever way. We start at the top left corner and carefully look at all the blocks above and to the left of the one we are touching. By using a secret trick with a math operation that flips bits back and forth, we create a new hidden number for every single spot on the grid based on all the blocks that came before it. This turns the original grid into a new one where every piece holds a combined mystery value. Once all the mystery values are ready, we put them all into a big bag together. To find the winner, we shake the bag and search for the number that takes the specific spot we are looking for, which is the one that ranks as the kth largest. We keep sorting and looking until that special number slides right into our hand.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| haoel | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| haoel | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 880: Decoded String at Index
- problem 912: Sort an Array
- problem 923: 3Sum With Multiplicity
- problem 973: K Closest Points to Origin
- problem 1010: Pairs of Songs With Total Durations Divisible by 60
- problem 1054: Distant Barcodes
- problem 1079: Letter Tile Possibilities
- problem 1090: Largest Values From Labels
- problem 1347: Minimum Number of Steps to Make Two Strings Anagram
- problem 1366: Rank Teams by Votes
- problem 1419: Minimum Number of Frogs Croaking
- problem 1814: Count Nice Pairs in an Array
- problem 1985: Find the Kth Largest Integer in the Array
- problem 2018: Check if Word Can Be Placed In Crossword
- problem 2150: Find All Lonely Numbers in the Array
- problem 2182: Construct String With Repeat Limit
- problem 2225: Find Players With Zero or One Losses
- problem 2232: Minimize Result by Adding Parentheses to Expression
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2284: Sender With Largest Word Count
- problem 2343: Query Kth Smallest Trimmed Number
- problem 2526: Find Consecutive Integers from a Data Stream
- problem 2844: Minimum Operations to Make a Special Number
- problem 2860: Happy Students
- problem 906: Super Palindromes
- problem 992: Subarrays with K Different Integers
- problem 1106: Parsing A Boolean Expression
- problem 1601: Maximum Number of Achievable Transfer Requests
- problem 2081: Sum of k-Mirror Numbers
- problem 2122: Recover the Original Array
- problem 2416: Sum of Prefix Scores of Strings
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality