Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Sort Matrix by Diagonals

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3446" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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: grid = [[1,7,3],[9,8,2],[4,5,6]] Output: [[8,2,3],[9,6,7],[4,5,1]] Explanation: The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order: [1, 8, 6] becomes [8, 6, 1]. [9, 5] and [4] remain unchanged. The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order: [7, 2] becomes [2, 7]. [3] remains unchanged. Example 2: Input: grid = [[0,1],[1,2]] Output: [[2,1],[1,0]] Explanation: The diagonals with a black arrow must be non-increasing, so [0, 2] is changed to [2, 0]. The other diagonals are already in the correct order. Example 3: Input: grid = [[1]] Output: [[1]] Explanation: Diagonals with exactly one element are already in order, so no changes are needed. Constraints: grid.length == grid[i].length == n 1 <= n <= 10 -105 <= grid[i][j] <= 105

Explanation

  • Separate and Sort Diagonals: Extract each diagonal into a list. Sort bottom-left diagonals in descending order and top-right diagonals in ascending order.
    • Reconstruct Matrix: Populate the original matrix with the sorted diagonal elements.
    • In-place operations: Minimize extra memory allocations to improve memory usage.
  • Runtime Complexity: O(n^2 log n), where n is the size of the grid. This is due to sorting the diagonals. The number of diagonals is O(n), and the average length of each diagonal is O(n), so the sorting takes O(n log n) time per diagonal. Storage Complexity: O(n) due to sorting lists. While the problem can be solved with O(1) extra space theoretically, practical considerations and the simplicity of the algorithm suggest to keep the diagonals extracted into temp arrays for readability.

Code

    def diagonal_sort(grid: list[list[int]]) -> list[list[int]]:
    """
    Sorts the diagonals of a square matrix as specified.

    Args:
        grid: The input n x n matrix.

    Returns:
        The modified matrix with sorted diagonals.
    """
    n = len(grid)

    def get_diagonal(matrix, row, col, direction):
        """Extracts a diagonal from the matrix."""
        diagonal = []
        while 0 <= row < n and 0 <= col < n:
            diagonal.append(matrix[row][col])
            row += direction[0]
            col += direction[1]
        return diagonal

    def put_diagonal(matrix, row, col, direction, diagonal):
        """Replaces a diagonal in the matrix with the sorted values."""
        index = 0
        while 0 <= row < n and 0 <= col < n:
            matrix[row][col] = diagonal[index]
            row += direction[0]
            col += direction[1]
            index += 1

    # Sort bottom-left diagonals (non-increasing)
    for i in range(n):
        diagonal = get_diagonal(grid, i, 0, (1, 1))
        diagonal.sort(reverse=True)
        put_diagonal(grid, i, 0, (1, 1), diagonal)

    for j in range(1, n):
        diagonal = get_diagonal(grid, 0, j, (1, 1))
        diagonal.sort(reverse=True)
        put_diagonal(grid, 0, j, (1, 1), diagonal)

    # Sort top-right diagonals (non-decreasing)
    for i in range(n):
        diagonal = get_diagonal(grid, i, 0, (1, 1))
        diagonal.sort()
        put_diagonal(grid, i, 0, (1, 1), diagonal)

    for j in range(1, n):
        diagonal = get_diagonal(grid, 0, j, (1, 1))
        diagonal.sort()
        put_diagonal(grid, 0, j, (1, 1), diagonal)

    #Correct for duplicates introduced by the double sorting.
    for i in range(n):
        diagonal = get_diagonal(grid, i, 0, (1, 1))
        diagonal.sort(reverse=True)
        put_diagonal(grid, i, 0, (1, 1), diagonal)

    for j in range(1, n):
        diagonal = get_diagonal(grid, 0, j, (1, 1))
        diagonal.sort()
        put_diagonal(grid, 0, j, (1, 1), diagonal)

    return grid

More from this blog

C

Chatmagic blog

2894 posts