Find the Kth Smallest Sum of a Matrix With Sorted Rows
Problem Statement
You get an m × n matrix mat. Every row is sorted from smallest to largest.
Pick exactly one number from each row. Add the picked numbers together to get one sum. With m rows there are n^m ways to pick, so there are that many sums (repeats count separately).
Return the k-th smallest of all those sums.
An m × n integer matrix mat whose rows are sorted, and an integer k.
One integer: the k-th smallest sum over all ways to pick one number from each row.
The nine sums are 3, 5, 7, 5, 7, 9, 13, 15, 17. Sorted, they are 3, 5, 5, 7, 7, 9, 13, 15, 17. The 5th is 7.
The seven smallest sums are 4, 5, 7, 8, 8, 8 and 9. The 7th is 9.
- • m == mat.length
- • n == mat[i].length
- • 1 ≤ m, n ≤ 40
- • 1 ≤ mat[i][j] ≤ 5000
- • 1 ≤ k ≤ min(200, n^m)
- • mat[i] is a non-decreasing array
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Build all n^m sums, sort them, and read position k
Start from row 0; for each next row, add its numbers to the kept sums, sort, and keep the first k
Merge the kept sums with each next row using the heap from the k smallest pair sums question
Build all n^m sums one row at a time, sort them, and read position k − 1. There are n^m choices, so this only works for tiny matrices.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like K-way Merge translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.