Print elements in sorted order using row-column wise sorted matrix
Pattern: Top K
Every row is a sorted list, so this is merging n sorted lists. Put the first value of each row in a min heap; pop the smallest, output it, and push the next value from its row. O(n² log n) for an n × n matrix.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given an n × n matrix whose rows and columns are each sorted ascending, return all its values in sorted order.
The catalogue has no practice link for this one.
Think first
- What is each row on its own?
- Which pattern combines k sorted lists?
- Do you also need the sorted columns?
Hints
Brute force, and why it fails
Copy all values and sort: O(n² log n²) = O(n² log n), and it ignores the sorted rows.
The key insight
Treating rows as sorted lists makes this a k-way merge, with a heap of only n items.
Dry run
| heap | 10 15 27 32 |
|---|
Matrix rows [10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]. The heap starts with 10, 15, 27, 32.
The plan
heap = [(mat[r][0], r, 0) for each row r]
while heap:
(v, r, c) = pop; output v
if c + 1 < n: push (mat[r][c + 1], r, c + 1)
Complexity
- Time
O(n² log n)- Space
O(n) besides the output
n² pops and pushes on a heap of n items.
Edge cases
- 1 × 1 matrix.
- Equal values across rows.
- A matrix where every row equals its row number plus a constant.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int[] sortedMatrix(int[][] mat) {
int n = mat.length, m = mat[0].length;
PriorityQueue<int[]> heap = new PriorityQueue<>((x, y) -> Integer.compare(x[0], y[0])); // {value, row, col}
for (int r = 0; r < n; r++) heap.add(new int[]{mat[r][0], r, 0}); // the smallest of each row
int[] out = new int[n * m];
for (int i = 0; i < out.length; i++) {
int[] top = heap.poll();
out[i] = top[0];
if (top[2] + 1 < m) heap.add(new int[]{mat[top[1]][top[2] + 1], top[1], top[2] + 1}); // its row's next
}
return out;
}
}C++
class Solution {
public:
vector<int> sortedMatrix(vector<vector<int>>& mat) {
int n = static_cast<int>(mat.size()), m = static_cast<int>(mat[0].size());
typedef pair<int, pair<int, int>> Item; // {value, {row, col}}
priority_queue<Item, vector<Item>, greater<Item>> heap;
for (int r = 0; r < n; r++) heap.push(make_pair(mat[r][0], make_pair(r, 0))); // the smallest of each row
vector<int> out;
while (!heap.empty()) {
Item top = heap.top();
heap.pop();
out.push_back(top.first);
int r = top.second.first, c = top.second.second;
if (c + 1 < m) heap.push(make_pair(mat[r][c + 1], make_pair(r, c + 1))); // its row's next
}
return out;
}
};Python
import heapq
class Solution:
def sortedMatrix(self, mat: list[list[int]]) -> list[int]:
heap = [(row[0], r, 0) for r, row in enumerate(mat)] # the smallest of each row
heapq.heapify(heap)
out = []
while heap:
v, r, c = heapq.heappop(heap)
out.append(v)
if c + 1 < len(mat[r]):
heapq.heappush(heap, (mat[r][c + 1], r, c + 1)) # its row's next
return outCommon mistakes
- Pushing every value at the start, which loses the k-way benefit.
- Pushing the next value from the wrong row.