Solving Leetcode Interviews in Seconds with AI: Largest Magic Square
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1895" 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
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 magic square has a size of 3. Every row sum, column sum, and diagonal sum of this magic square is equal to 12. - Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12 - Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12 - Diagonal sums: 5+4+3 = 6+4+2 = 12 Example 2: Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]] Output: 2 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 1 <= grid[i][j] <= 106
Explanation
Here's a breakdown of the approach, complexities, and the Python code:
High-Level Approach:
- Iterate through possible square sizes (from the smaller of
mandndown to 1). - For each size, slide a window across the grid, checking if the current square is a magic square.
- Efficiently calculate row, column, and diagonal sums using prefix sums to avoid redundant calculations.
- Iterate through possible square sizes (from the smaller of
Complexity:
- Runtime: O(m*n*min(m, n)) where
mis the number of rows andnis the number of columns in the grid. - Storage: O(m*n) for the prefix sum arrays.
- Runtime: O(m*n*min(m, n)) where
Python Code:
Code
def largestMagicSquare(grid):
m, n = len(grid), len(grid[0])
max_size = min(m, n)
def is_magic_square(row_start, col_start, size):
row_sums = [0] * size
col_sums = [0] * size
diag1_sum = 0
diag2_sum = 0
for i in range(size):
for j in range(size):
row_sums[i] += grid[row_start + i][col_start + j]
col_sums[j] += grid[row_start + i][col_start + j]
diag1_sum += grid[row_start + i][col_start + i]
diag2_sum += grid[row_start + i][col_start + size - 1 - i]
if len(set(row_sums)) != 1 or len(set(col_sums)) != 1 or row_sums[0] != col_sums[0] or row_sums[0] != diag1_sum or row_sums[0] != diag2_sum:
return False
return True
for size in range(max_size, 0, -1):
for r in range(m - size + 1):
for c in range(n - size + 1):
if is_magic_square(r, c, size):
return size
return 1