Assign Compact Ranks to a Matrix Preserving Row and Column Order

Last updated: November 29, 2026

Quick Overview

Given an m by n integer matrix, assign each cell a positive rank so that within every row and every column, a larger value gets a larger rank, equal values get equal ranks, and ranks are as small as possible. Return the rank matrix.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given an m by n integer matrix, assign each cell a positive rank so that within every row and every column, a larger value gets a larger rank, equal values get equal ranks, and ranks are as small as possible. Return the rank matrix.

This is one of the harder union-find questions seen in Google onsites, relevant to compressing values in search ranking tables while keeping row and column order. The interviewer checks that you process values in sorted order, use union-find to tie equal values that share a row or column, and give each tied group one rank.

What the Interviewer Expects
  • Processes cells grouped by value in increasing order
  • Tracks the current max rank per row and per column
  • Unions rows and columns that share cells of the same value
  • Assigns each group the max over its cells of (row rank, column rank) + 1
  • Updates row and column ranks after each value is processed
Key Topics to Cover
Union-Find
Sorting
Matrix
Rank Compression
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
  • Prove the resulting ranks are minimal.
  • What if equal values in the same row may get different ranks?
  • How would you parallelize this for a very large matrix?
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: non-empty m by n integer matrix.
  • Constraints apply within each row and each column only.
  • Equal values in the same row or column must share a rank, which can chain across the matrix.
  • Out...
High-Level Design

Process distinct values from smallest to largest. For the cells with the current value, equal values in one row or one column must share a rank, and that requirement chains: two cells in different row...


Submit Your Answer
Markdown supported