Posts

Showing posts from February, 2025

Diagonals

Image
We need to sort the diagonals of a matrix. The approach that I use here is the following: 1. Create a Hashtable where the key is the diagonal index. The diagonal index is just the row-col 2. Traverse the matrix adding the elements as a list to the corresponding Hashtable entry 3. Traverse the Hashtable and sort each list (you need to store in a different Hashtable) 4. Traverse the matrix again. Now that you have the diagonal index, get the corresponding element using the Hashtable 5. Remove the corresponding element from the list, depending whether you're sorting up or down Code is down below, cheers, ACC Sort Matrix by Diagonals - LeetCode You are given an  n x n  square matrix of integers  grid . Return the matrix such that: The diagonals in the  bottom-left triangle  (including the middle diagonal) are sorted in  non-increasing order . The diagonals in the  top-right triangle  are sorted in  non-decreasing order .   Example 1: Input: ...