You are given an m x n integer matrix grid containing distinct positive integers. You have to replace each integer in the matrix with a positive integer satisfying the following conditions:
1. The relative order of every two elements that are in the same row or column should stay the same after the replacements.
2. The maximum number in the matrix after the replacements should be as small as possible.
The relative order stays the same if for all pairs of elements in the original matrix such that grid[r1][c1] > grid[r2][c2] where either r1 == r2 or c1 == c2, then it must be true that grid[r1][c1] > grid[r2][c2] after the replacements.
For example, if grid = [[2, 4, 5], [7, 3, 9]] then a good replacement could be either grid = [[1, 2, 3], [2, 1, 4]] or grid = [[1, 2, 3], [3, 1, 4]].
Return the resulting matrix. If there are multiple answers, return any of them.
Input & Output
Example 1 — Basic Grid
$Input:grid = [[2,4,5],[7,3,9]]
›Output:[[1,2,3],[2,1,4]]
💡 Note:Process elements by value: 2→rank 1, 3→rank 1, 4→rank 2, 5→rank 3, 7→rank 2, 9→rank 4. Each rank respects row/column ordering constraints.
Example 2 — Single Row
$Input:grid = [[1,3,2]]
›Output:[[1,3,2]]
💡 Note:In a single row, elements must maintain their relative order: 1 < 2 < 3, so the minimum assignment is [1,3,2].
Example 3 — Single Column
$Input:grid = [[5],[2],[8]]
›Output:[[2],[1],[3]]
💡 Note:In a single column, we process 2→1, 5→2, 8→3 to maintain the constraint 2 < 5 < 8.
The key insight is to process elements in sorted order and assign each the minimum rank that maintains row/column ordering constraints. Use coordinate compression: for each element, assign max(current_row_max, current_col_max) + 1. Best approach is coordinate compression with Time: O(mn log(mn)), Space: O(mn).
Common Approaches
✓
Brute Force Constraint Checking
⏱️ Time: O((mn)!)
Space: O(mn)
Generate all possible assignments of values 1 to m*n and check if each assignment maintains the relative order constraints for rows and columns. This approach is extremely inefficient but conceptually straightforward.
Coordinate Compression with Union-Find
⏱️ Time: O(mn log(mn))
Space: O(mn)
Elements in the same row or column that need to maintain relative order form connected components. Use union-find to identify these components, then assign ranks within each component to minimize the maximum value.
Brute Force Constraint Checking — Algorithm Steps
Step 1: Generate all permutations of values 1 to m*n
Step 2: For each permutation, check if it satisfies row and column ordering constraints
Step 3: Return the first valid assignment found
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Generate Permutations
Create all possible ways to assign values 1-6
2
Check Constraints
Verify each assignment maintains row/column order
3
Return Valid
Return first assignment that satisfies all constraints
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct {
int value, row, col;
} Element;
int compare(const void* a, const void* b) {
Element* ea = (Element*)a;
Element* eb = (Element*)b;
return ea->value - eb->value;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int** solution(int** grid, int gridSize, int* gridColSize, int* returnSize, int** returnColumnSizes) {
int m = gridSize, n = gridColSize[0];
// Create list of elements and sort by value
Element* elements = malloc(m * n * sizeof(Element));
int idx = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
elements[idx++] = (Element){grid[i][j], i, j};
}
}
qsort(elements, m * n, sizeof(Element), compare);
// Initialize result matrix
int** result = malloc(m * sizeof(int*));
*returnColumnSizes = malloc(m * sizeof(int));
*returnSize = m;
for (int i = 0; i < m; i++) {
result[i] = calloc(n, sizeof(int));
(*returnColumnSizes)[i] = n;
}
// Process elements in sorted order
for (int k = 0; k < m * n; k++) {
int row = elements[k].row;
int col = elements[k].col;
// Find the minimum rank needed for this position
int minRank = 1;
// Check all elements in the same row
for (int j = 0; j < n; j++) {
if (result[row][j] > 0) { // Already assigned
int newRank = result[row][j] + 1;
if (newRank > minRank) {
minRank = newRank;
}
}
}
// Check all elements in the same column
for (int i = 0; i < m; i++) {
if (result[i][col] > 0) { // Already assigned
int newRank = result[i][col] + 1;
if (newRank > minRank) {
minRank = newRank;
}
}
}
result[row][col] = minRank;
}
free(elements);
return result;
}
int** parseGrid(const char* input, int* rows, int* cols, int** colSizes) {
char buffer[10000];
strcpy(buffer, input);
*rows = 0;
*cols = 0;
// Count rows and columns
char* p = buffer;
while (*p && *p != '[') p++;
if (*p == '[') p++;
// Count rows by counting '[' after first one
char* temp = p;
while (*temp) {
if (*temp == '[') (*rows)++;
temp++;
}
// Allocate memory
int** grid = malloc(*rows * sizeof(int*));
*colSizes = malloc(*rows * sizeof(int));
int row = 0;
while (*p && row < *rows) {
while (*p && *p != '[') p++;
if (*p == '[') {
p++;
// Find end of this row
char* rowEnd = p;
int brackets = 1;
while (*rowEnd && brackets > 0) {
if (*rowEnd == '[') brackets++;
if (*rowEnd == ']') brackets--;
rowEnd++;
}
// Count numbers in this row
char* counter = p;
int numCount = 0;
while (counter < rowEnd - 1) {
while (counter < rowEnd - 1 && !isdigit(*counter) && *counter != '-') counter++;
if (counter < rowEnd - 1 && (isdigit(*counter) || *counter == '-')) {
numCount++;
while (counter < rowEnd - 1 && (isdigit(*counter) || *counter == '-')) counter++;
}
}
if (*cols == 0) *cols = numCount;
(*colSizes)[row] = numCount;
grid[row] = malloc(numCount * sizeof(int));
// Parse numbers
int col = 0;
while (*p && *p != ']' && col < numCount) {
while (*p && !isdigit(*p) && *p != '-' && *p != ']') p++;
if (*p == ']') break;
if (isdigit(*p) || *p == '-') {
grid[row][col++] = (int)strtol(p, &p, 10);
}
}
while (*p && *p != ']') p++;
if (*p == ']') p++;
row++;
}
}
return grid;
}
int main() {
char input[10000];
if (fgets(input, sizeof(input), stdin)) {
// Remove newline
input[strcspn(input, "\n")] = 0;
int rows, cols;
int* colSizes;
int** grid = parseGrid(input, &rows, &cols, &colSizes);
int returnSize;
int* returnColumnSizes;
int** result = solution(grid, rows, colSizes, &returnSize, &returnColumnSizes);
printf("[");
for (int i = 0; i < returnSize; i++) {
if (i > 0) printf(",");
printf("[");
for (int j = 0; j < returnColumnSizes[i]; j++) {
if (j > 0) printf(",");
printf("%d", result[i][j]);
}
printf("]");
}
printf("]\n");
// Free memory
for (int i = 0; i < rows; i++) {
free(grid[i]);
free(result[i]);
}
free(grid);
free(result);
free(colSizes);
free(returnColumnSizes);
}
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O((mn)!)
Generate all permutations of mn elements and check each one
n
2n
✓ Linear Growth
Space Complexity
O(mn)
Store the current permutation and result matrix
n
2n
⚡ Linearithmic Space
15.6K Views
MediumFrequency
~35 minAvg. Time
425 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.