Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count Square Submatrices with All Ones

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1277" 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

Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. Example 1: Input: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15. Example 2: Input: matrix = [ [1,0,1], [1,1,0], [1,1,0] ] Output: 7 Explanation: There are 6 squares of side 1. There is 1 square of side 2. Total number of squares = 6 + 1 = 7. Constraints: 1 <= arr.length <= 300 1 <= arr[0].length <= 300 0 <= arr[i][j] <= 1

Explanation

Here's an efficient solution to count square submatrices with all ones:

  • Dynamic Programming: The core idea is to use dynamic programming to store the size of the largest square ending at each cell. The value at dp[i][j] represents the side length of the largest square submatrix with all 1s ending at matrix[i][j].

  • Bottom-Up Approach: Build the dp table from top-left to bottom-right. If matrix[i][j] is 0, then dp[i][j] is 0. Otherwise, dp[i][j] is min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1.

  • Accumulate the Count: Sum up all the values in the dp table. Each dp[i][j] value contributes to the total count of square submatrices.

  • Time & Space Complexity: O(m n) time complexity, O(m n) space complexity, where m is the number of rows and n is the number of columns.

Code

    def countSquares(matrix):
    """
    Counts the number of square submatrices with all ones in a given matrix.

    Args:
        matrix: A list of lists of integers representing the matrix.

    Returns:
        The number of square submatrices with all ones.
    """
    m = len(matrix)
    n = len(matrix[0])
    dp = [[0] * n for _ in range(m)]
    count = 0

    for i in range(m):
        for j in range(n):
            if matrix[i][j] == 1:
                if i == 0 or j == 0:
                    dp[i][j] = 1
                else:
                    dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1
                count += dp[i][j]

    return count

More from this blog

C

Chatmagic blog

2894 posts