Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Maximal Rectangle

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "85" 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 rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. Example 1: Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 6 Explanation: The maximal rectangle is shown in the above picture. Example 2: Input: matrix = [["0"]] Output: 0 Example 3: Input: matrix = [["1"]] Output: 1 Constraints: rows == matrix.length cols == matrix[i].length 1 <= row, cols <= 200 matrix[i][j] is '0' or '1'.

Explanation

Here's an efficient solution to find the largest rectangle containing only 1's in a binary matrix:

  • Treat each row as the base: For each row, consider it as the base of a histogram. The height of each bar in the histogram is determined by the consecutive 1's extending upwards from that row.
  • Calculate histogram heights: Build a heights matrix where heights[i][j] represents the consecutive 1's above and including matrix[i][j].
  • Largest Rectangular Area in Histogram: For each row's histogram (represented by heights[i]), use an efficient algorithm (stack-based) to find the largest rectangular area in that histogram. Update the maximum area found so far.

  • Runtime Complexity: O(rows cols) , *Storage Complexity: O(cols)

Code

    def largestRectangleArea(heights):
    """
    Calculates the largest rectangular area in a histogram represented by heights.
    """
    max_area = 0
    stack = []  # (index, height)

    for i, h in enumerate(heights):
        start = i
        while stack and stack[-1][1] > h:
            index, height = stack.pop()
            max_area = max(max_area, height * (i - index))
            start = index  #Important for consecutive pops
        stack.append((start, h))

    while stack:
        index, height = stack.pop()
        max_area = max(max_area, height * (len(heights) - index))

    return max_area


def maximalRectangle(matrix):
    """
    Finds the largest rectangle containing only 1's in a binary matrix.
    """
    if not matrix:
        return 0

    rows = len(matrix)
    cols = len(matrix[0])

    heights = [0] * cols
    max_area = 0

    for i in range(rows):
        for j in range(cols):
            if matrix[i][j] == "1":
                heights[j] += 1
            else:
                heights[j] = 0

        max_area = max(max_area, largestRectangleArea(heights))

    return max_area

More from this blog

C

Chatmagic blog

2894 posts