Problem 378

Abstract / Summary

Find the kth smallest number in a matrix where each row and column is sorted in ascending order.

Note

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

Python 0378.py

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        n = len(matrix)
        heap = []

        result = matrix[0][0]
        next = [0] * n
        next[0] += 1

        while k > 1:
            low = 99999999999
            ymin = 0
            for y in range(len(next)):
                x = next[y]
                if x < n and low > matrix[y][x]:
                    low = matrix[y][x]
                    ymin = y

            result = low
            next[ymin] += 1
            k -= 1

        return result
23 lines | 576 bytes | submitted September 5, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Heap (Priority Queue)
  • Matrix
  • 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 provided implementation computes the k-th smallest element in a square matrix where each row and each column is sorted in non-decreasing order. It does so by iteratively selecting the smallest candidate among the next unexamined elements of every row, advancing the pointer for the row that contributed the current minimum, and repeating until the desired rank is reached. The algorithm maintains only a few auxiliary structures: the matrix size, a one-dimensional list tracking column positions for each row, and a variable holding the current result.

Initialization

The function begins by determining the dimension of the matrix and preparing the tracking structures.

n = len(matrix)
heap = []

result = matrix[0][0]
next = [0] * n
next[0] += 1

n stores the matrix dimension. Although a variable named heap is created, it remains unused throughout the routine. result is seeded with the top-left element, which is the smallest value in the entire matrix. The list next holds, for each row, the column index of the next candidate element to consider. All entries start at 0, and the first row’s pointer is immediately advanced to 1 because its initial element has already been accounted for in result.

Main Iteration

The core of the algorithm is a loop that runs until the rank k is reduced to 1. Each pass identifies the smallest among the current candidates and updates the state accordingly.

while k > 1:
    low = 99999999999
    ymin = 0
    for y in range(len(next)):
        x = next[y]
        if x < n and low > matrix[y][x]:
            low = matrix[y][x]
            ymin = y

    result = low
    next[ymin] += 1
    k -= 1

Selection of the Minimum Candidate

Inside the loop, low is initialized to a very large sentinel value, and ymin records the row index of the smallest candidate found. The for loop iterates over each row index y. For a given row, x = next[y] fetches the column index of the next unprocessed element. The condition x < n ensures that the algorithm does not read beyond the matrix bounds, effectively handling rows that have already exhausted all their elements. When a candidate value matrix[y][x] is smaller than the current low, both low and ymin are updated. This scan guarantees that the globally smallest among the pending elements is selected.

Updating State

After the minimum is identified, result is set to this value, the pointer for the contributing row (next[ymin]) is incremented to skip the element just used, and k is decremented to reflect that one more rank has been satisfied. The loop repeats until k reaches 1, at which point result holds the k-th smallest element.

Edge Cases Handled

When the matrix consists of a single element (n == 1), the initialization sets result to that element and next[0] becomes 1. The loop condition while k > 1 fails for any k equal to 1, so the function returns the sole element directly, correctly handling the smallest possible input.

If k equals 1 for a larger matrix, the loop is bypassed entirely, and the function returns the top-left element, which is the global minimum due to the sorted rows and columns. This case is covered without extra branching.

Rows that have already contributed all their elements are naturally excluded from consideration because their next[y] value reaches n. The guard x < n prevents out-of-range access, so the algorithm gracefully skips exhausted rows while still scanning the full next list.

Duplicate values across rows or columns do not affect correctness. The comparison low > matrix[y][x] selects the first encountered minimum, and subsequent duplicates are treated as separate candidates in later iterations, preserving the correct ordering for the k-th smallest element.

Performance Optimizations

The implementation avoids the overhead of a priority queue by using a plain list next to track column positions. This choice reduces auxiliary memory usage to O(n) and eliminates the need for heap operations such as insertion and extraction, which would involve additional logarithmic factors. The linear scan over next in each iteration is straightforward and benefits from cache locality, as the loop accesses contiguous entries in both the next list and the matrix rows.

By initializing low with a large constant rather than using Python’s float('inf'), the code sidesteps the creation of a special floating-point object, marginally reducing allocation overhead in tight loops.

The early advancement of the first row’s pointer (next[0] += 1) eliminates the need to treat the first element as a special case inside the loop, allowing the main iteration to operate uniformly for all subsequent selections.

Overall, the algorithm achieves a balance between simplicity and efficiency, leveraging the sorted nature of the matrix while keeping the runtime footprint modest.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big grid made of squares, where each square has a number inside. The numbers are lined up neatly from smallest to biggest as you go across and down. The goal is to find the number that holds the spot of the k-th smallest value in this whole grid.

Think of a treasure hunt where the grid is a map. A small list is created to keep track of which row to look at next, and it starts by pointing at the very first number. Then, the computer investigates the grid row by row. It looks at the current numbers in each row that could be the next smallest one, picks the winner, and moves its pointer forward in that specific row. This continues step by step. Each time the computer finds a new smallest number, it ticks off one count from k. By the time the final count is reached, the number found during that last step is the answer.

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 = 4 | μ = 4.63 | σ = 1.49

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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++ Python Java
leetcode.ca C++ Python Java Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
Garvit244 Python
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
MacJim C++
muhammadfarhankt Go
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
MacJim C++
muhammadfarhankt Go
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
42 links | 30 authors | 10 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

6 easy 5 medium
12 solutions   September 5, 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