#1895

Largest Magic Square

Medium
ArrayMatrixPrefix SumDynamic ProgrammingPrefix Sums
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n * min(m, n))
O(m * n)
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

The optimal solution uses dynamic programming to build on previously computed results, allowing us to efficiently check for larger magic squares without recalculating sums from scratch.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP table to store the size of the largest magic square ending at each cell.
  2. 2Step 2: Iterate through the grid, and for each cell, check if it can be the bottom-right corner of a magic square.
  3. 3Step 3: Use previously computed values to determine the size of the magic square that can be formed.
solution.py13 lines
1def largestMagicSquare(grid):
2    m, n = len(grid), len(grid[0])
3    dp = [[0] * n for _ in range(m)]
4    max_size = 1
5    for i in range(m):
6        for j in range(n):
7            if i == 0 or j == 0:
8                dp[i][j] = 1
9            else:
10                if grid[i][j] == grid[i-1][j] == grid[i][j-1] == grid[i-1][j-1]:
11                    dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
12            max_size = max(max_size, dp[i][j])
13    return max_size

Complexity note: The time complexity is linear with respect to the number of cells in the grid, as we only iterate through the grid once and use previously computed results to determine the size of magic squares.

  • 1Magic squares require equal sums across rows, columns, and diagonals.
  • 2Dynamic programming can optimize checking for larger squares by leveraging smaller results.

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