#3446

Sort Matrix by Diagonals

Medium
ArraySortingMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n² log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n² log n)Space O(n)

We can optimize the process by directly sorting the diagonals while traversing the matrix, which reduces the number of passes over the data.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a map to hold the diagonal values as we traverse the matrix.
  2. 2Step 2: For each diagonal, sort the values in the required order during the traversal.
  3. 3Step 3: Place the sorted values back into the matrix in a single pass.
solution.py25 lines
1# Full working Python code
2from collections import defaultdict
3
4def diagonalSort(grid):
5    n = len(grid)
6    diagonals = defaultdict(list)
7
8    # Step 1: Fill diagonals
9    for i in range(n):
10        for j in range(n):
11            diagonals[i - j].append(grid[i][j])
12
13    # Step 2: Sort diagonals
14    for key in diagonals:
15        if key <= 0:
16            diagonals[key].sort(reverse=True)  # Bottom-left
17        else:
18            diagonals[key].sort()  # Top-right
19
20    # Step 3: Place sorted values back
21    for i in range(n):
22        for j in range(n):
23            grid[i][j] = diagonals[i - j].pop(0)
24
25    return grid

Complexity note: The time complexity is O(n² log n) due to sorting the diagonal values. The space complexity remains O(n) for storing the diagonal values.

  • 1Understanding how to identify and sort diagonals is crucial for solving matrix-related problems.
  • 2Using a map to store diagonal values helps in organizing and sorting them efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.