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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

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
Diagonal Traversal
Grouping by Key
Sorting
Counting Sort
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • Input: mat, m x n ints, sorted in place.
  • Every cell with the same r - c lies on the same diagonal.
  • After sorting, values along each diagonal ascend as r increases....
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...


Submit Your Answer
Markdown supported