Sort Each Top-Left to Bottom-Right Diagonal of a Ranking Matrix
Last updated: November 29, 2026
Quick Overview
Given an m x n matrix of integers, sort every diagonal that runs from top-left to bottom-right in ascending order, in place, and return the matrix.
0
0
0 solved
Given an m x n matrix of integers, sort every diagonal that runs from top-left to bottom-right in ascending order, in place, and return the matrix.
A Google screen problem testing whether you can group cells by a stable key and write them back. The interviewer expects the r - c invariant and a discussion of counting sort when values are small, such as rating buckets.
What the Interviewer Expects
- Groups cells by the invariant r - c
- Sorts each group and writes values back in order
- Handles non-square matrices
- States O(mn log(min(m, n))) time
- Offers counting sort for a small value range
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Values are in 1..100; can you do better than comparison sort?
- Sort anti-diagonals instead.
- Do it with O(1) extra space beyond a single diagonal buffer.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
mat, m x n ints, sorted in place. - Every cell with the same
r - clies on the same diagonal. - After sorting, values along each diagonal ascend as
rincreases....
High-Level Design
There are m + n - 1 diagonals. Walk each one from its starting cell (the first row or first column), collect values into a buffer, sort, and write them back along the same walk. This uses one buffer...