Similar Problems

Similar Problems not available

Largest Magic Square - Leetcode Solution

Companies:

LeetCode:  Largest Magic Square Leetcode Solution

Difficulty: Medium

Topics: matrix prefix-sum array  

The Largest Magic Square problem on LeetCode is a problem that requires you to find the size of the largest magic square in a given matrix. A magic square is a square matrix where the sum of each row, each column, and each diagonal is the same constant.

Here's a detailed solution to the problem:

  1. First, we need to check all possible sizes of magic squares. Since the matrix could have different sizes, we need to iterate through all possible sizes starting from the minimum size of 2 and ending with the maximum size of min(rows, cols).

  2. Next, for each possible size, we need to iterate through all possible positions where we can create a magic square of this size. To create a magic square, we need to check if the sum of each row, column, and diagonal is the same constant.

  3. To check if a matrix is a magic square, we can start by calculating the sum of the first row. We can then check if the sum of all other rows is equal to this sum. Similarly, we can calculate the sum of the first column and check if the sum of all other columns is equal to this sum. Finally, we need to check if the sum of both diagonals is equal to the same constant.

  4. If we find a magic square of a particular size, we can update the maximum size found so far.

  5. Finally, we return the maximum size found.

Here's the Python code for the solution:

class Solution:
    def largestMagicSquare(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        max_size = 1
        
        # iterate through all possible sizes
        for size in range(2, min(rows, cols)+1):
            # iterate through all possible positions
            for i in range(rows-size+1):
                for j in range(cols-size+1):
                    # check if the matrix is a magic square
                    sum_diag1 = sum_diag2 = 0
                    for k in range(size):
                        sum_diag1 += grid[i+k][j+k]
                        sum_diag2 += grid[i+k][j+size-k-1]
                        if sum(grid[i+k][j:j+size]) != sum(grid[row][j:j+size]) or sum(grid[i:i+size][j+k]) != sum(grid[i:i+size][col] for col in range(j, j+size)):
                            break
                    else:
                        # update the maximum size found so far
                        max_size = size
        
        return max_size

The time complexity of this solution is O(n^4), where n is the size of the matrix. This is because we're iterating through all possible sizes and positions of the magic square. The space complexity is O(1) since we're not using any extra space.

Largest Magic Square Solution Code

1