Advertisement

Largest Magic Square - LeetCode 1895 Solution

Largest Magic Square - Complete Solution Guide

Largest Magic Square is LeetCode problem 1895, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal . The integers in the magic square do not have to be distinct . Every 1 x 1 grid is trivially a magic square . Given an m x n integer grid , return the size (i.e., the side length k ) of the largest magic square that can be found within this grid . Example 1: Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]] Output: 3 Explanation: The largest mag

Detailed Explanation

The problem asks us to find the largest magic square within a given m x n grid of integers. A k x k magic square is a square grid where the sum of each row, column, and both diagonals is equal. We need to return the size (k) of the largest magic square found within the input grid. If no magic square larger than 1x1 exists, we return 1 since every 1x1 grid is considered a magic square. The integers within the magic square don't have to be distinct, and the constraints limit the grid size to 50x50 with integer values up to 10^6.

Solution Approach

The solution utilizes prefix sums to efficiently calculate the sums of rows and columns within potential magic squares. It iterates through possible square sizes (k) from the largest possible size down to 2. For each size, it iterates through all possible top-left corners of a k x k square within the grid. For each potential square, it first checks if the sums of both diagonals are equal. If not, it moves on to the next potential square. If the diagonals sums are equal, it calculates the sums of all rows and columns using the precomputed prefix sums. If all row, column, and diagonal sums are equal, the current square is a magic square, and the size k is returned. If no magic square larger than 1 is found, the function returns 1.

Step-by-Step Algorithm

  1. Step 1: Calculate prefix sums for each row of the grid. `prefix_row[r][c+1]` stores the sum of `grid[r][0]` to `grid[r][c]` inclusive.
  2. Step 2: Calculate prefix sums for each column of the grid. `prefix_col[r+1][c]` stores the sum of `grid[0][c]` to `grid[r][c]` inclusive.
  3. Step 3: Iterate through possible square sizes `k` from `min(m, n)` down to 2. This ensures we find the *largest* magic square first.
  4. Step 4: Iterate through possible top-left corners `(r, c)` for a `k x k` square within the grid, ensuring the square remains within the grid boundaries.
  5. Step 5: Calculate the sum of the main diagonal (`diag1_sum`) and the anti-diagonal (`diag2_sum`).
  6. Step 6: If `diag1_sum` is not equal to `diag2_sum`, the current `k x k` square cannot be a magic square, so continue to the next potential square.
  7. Step 7: If the diagonal sums are equal, calculate row and column sums using prefix sums. `row_sum = prefix_row[r + i][c + k] - prefix_row[r + i][c]` and `col_sum = prefix_col[r + k][c + i] - prefix_col[r][c + i]`.
  8. Step 8: If any row or column sum is not equal to the diagonal sums (`target_sum`), the square is not a magic square, so continue to the next potential square.
  9. Step 9: If all row, column and diagonal sums are equal, the current `k x k` square is a magic square. Return `k`.
  10. Step 10: If no magic square of size greater than 1 is found, return 1 (since every 1x1 square is a magic square).

Key Insights

  • Insight 1: Prefix sums can significantly reduce the time complexity of calculating row and column sums for each potential magic square.
  • Insight 2: Starting the search for magic squares from the largest possible size (min(m, n)) and working downwards allows early termination as soon as a magic square is found.
  • Insight 3: The diagonal sums must be checked first, as if they are not equal the square cannot be a magic square, and the rows and columns need not be checked saving time.

Complexity Analysis

Time Complexity: O((min(m,n)^3) * (m * n))

Space Complexity: O(m * n)

Topics

This problem involves: Array, Matrix, Prefix Sum.

Companies

Asked at: Wayfair.