Problem 1329

Abstract / Summary

Sort each diagonal of the matrix from top right to bottom left in ascending order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1329.py

class Solution:
    def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
        width  = len(mat[0])
        height = len(mat)

        # assign each diagonal an ID
        getDiagonal = lambda x, y: y - x
        # store values of each diagonal
        diagonals = defaultdict(list)

        for y in range(height):
            for x in range(width):
                d = getDiagonal(x, y)
                diagonals[d].append(mat[y][x])

        for d in diagonals:
            diagonals[d].sort()

        for y in range(height):
            for x in range(width):
                d = getDiagonal(x, y)
                mat[y][x] = diagonals[d].pop(0)

        return mat
24 lines | 709 bytes | submitted December 23, 2023 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation rearranges the elements of a two-dimensional integer matrix so that each diagonal that runs from the top-left to the bottom-right is sorted in non-decreasing order. The algorithm proceeds in three conceptual phases: identification of diagonal groups, sorting of the collected values, and writing the sorted values back into the original matrix. Throughout the process the code relies on Python’s built-in data structures to keep the logic concise and to avoid explicit index arithmetic beyond what is necessary for diagonal identification.

Identification of Diagonal Groups

A diagonal is uniquely defined by the difference between its column index x and its row index y. The lambda expression getDiagonal = lambda x, y: y - x computes this identifier for any cell. By iterating over every row y and column x, the algorithm populates a dictionary that maps each diagonal identifier to a list of the values that belong to that diagonal.

width  = len(mat[0])
height = len(mat)

getDiagonal = lambda x, y: y - x
diagonals = defaultdict(list)

for y in range(height):
    for x in range(width):
        d = getDiagonal(x, y)
        diagonals[d].append(mat[y][x])

Because the dictionary is a defaultdict(list), a new list is automatically created the first time a particular diagonal identifier is encountered. This eliminates the need for explicit existence checks and keeps the code focused on the core logic.

Sorting of Collected Values

Once all values have been grouped by diagonal, each list is sorted in place. The sort method of Python lists implements an efficient adaptive sorting algorithm (Timsort) that performs well on partially ordered data, which is often the case for matrix diagonals.

for d in diagonals:
    diagonals[d].sort()

Sorting each diagonal independently guarantees that the final matrix will have every diagonal ordered without affecting the relative ordering of elements on different diagonals.

Writing Sorted Values Back

The final phase walks the matrix a second time, recomputing the diagonal identifier for each cell and replacing the original value with the next smallest element from the corresponding sorted list. The pop(0) operation removes the first element of the list, which is the smallest remaining value after sorting.

for y in range(height):
    for x in range(width):
        d = getDiagonal(x, y)
        mat[y][x] = diagonals[d].pop(0)

Because each diagonal list is exhausted exactly as many times as it contains elements, the algorithm restores the matrix in a single pass after sorting.

Edge Cases Handled

The algorithm works correctly for matrices that are not square, including those with a single row or a single column. The diagonal identifier y - x naturally distinguishes each diagonal regardless of the matrix’s aspect ratio, so rectangular shapes are treated without special casing.

Matrices that contain negative numbers, zero, or duplicate values are also handled gracefully because the built-in sort method orders elements according to their natural numeric ordering, and duplicate entries remain adjacent after sorting, preserving the required non-decreasing order.

When the input matrix consists of a single element, the outer loops iterate once, the diagonal dictionary receives one entry, sorting a list of length one is a no-op, and the final write-back restores the original value. Thus the implementation correctly returns the unchanged matrix for this minimal case.

Performance Optimizations Observed

The use of a defaultdict eliminates conditional checks for key existence, reducing overhead in the inner loops that run for every cell. Grouping values by diagonal before sorting ensures that each element participates in exactly one sort operation, avoiding repeated comparisons across diagonals.

Sorting each diagonal independently leverages the fact that the total number of elements across all diagonals equals the total number of matrix cells. Consequently, the overall work performed by the sorting step is proportional to the sum of the lengths of the diagonal lists, which is optimal for the problem’s constraints.

The second traversal that writes sorted values back uses pop(0) on each diagonal list. Although pop(0) has linear cost for a single list, the cumulative cost across all diagonals remains linear in the number of matrix elements because each element is removed exactly once. This design choice keeps the implementation simple while still achieving overall linear-time behavior for the reconstruction phase.

By separating the concerns of collection, sorting, and reconstruction, the code maintains clear data flow and benefits from Python’s highly optimized list operations, resulting in an implementation that is both concise and performant for matrices of typical sizes encountered in practice.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a square grid filled with scattered numbers, much like toy blocks spread across a floor. This code acts like a very organized robot trying to tidy them up.

First, the robot looks at the grid and identifies every slanted line of boxes, which are called diagonals. Think of these like rows of beads on a string that run from the top left corner down to the bottom right corner. To keep track of which bead belongs to which string, the robot gives each slanted line its own special label.

The robot walks through the grid square by square. Every time it finds a number, it looks at the slanted line that number belongs to and puts it into a pile for that specific line. Now the robot has a collection of piles, with each pile holding all the numbers found on one diagonal string.

Next, the robot picks up each pile one by one and sorts the numbers inside from the smallest to the largest. It is essentially making sure the little numbers come first and the big numbers come last on every string.

Finally, the robot walks through the grid one more time. It looks at the slanted line for each square it visits, grabs the smallest number from that specific sorted pile, and places it into the grid. By the time the robot finishes visiting every square, all the numbers have been rearranged so that every diagonal line is perfectly sorted in order.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.04 | σ = 0.92

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python C# Go Rust TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
34 links | 21 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality