Problem 1738

Abstract / Summary

Given a list of integers and an integer k, find the kth largest value obtained by xor-ing any two numbers from the list.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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];
    }
};
26 lines | 1017 bytes | submitted September 28, 2023 | GitHub   14% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.63 | σ = 1.52

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
24 links | 14 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

32 solutions   September 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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