🧱 Beginner-Friendly Guide 'Maximize Area of Square Hole in Grid' – LeetCode 2943 (C++, Python, JavaScript)

Published: (January 15, 2026 at 12:13 AM EST)
4 min read
Source: Dev.to

Source: Dev.to

Problem Overview

You are given:

  • Two integers n and m, the numbers of internal horizontal and vertical bars in a grid.
  • Two arrays, hBars and vBars, listing the specific bars that can be removed.

The grid consists of cells separated by bars. Removing consecutive bars merges the spaces between the remaining fixed bars.

  • Removing one bar creates a gap of 2 units.
  • Removing k consecutive bars creates a gap of k + 1 units.

Your goal is to find the maximum area of a square hole that can be created by removing any number of the removable bars.

Key Insight

The problem can be split into two independent 1‑D sub‑problems:

  1. Horizontal direction – find the longest sequence of consecutive removable horizontal bars.
  2. Vertical direction – find the longest sequence of consecutive removable vertical bars.

If the longest horizontal sequence has length h, the maximum horizontal gap is h + 1.
Similarly, a vertical sequence of length v yields a vertical gap of v + 1.

Since the hole must be a square, its side length is limited by the smaller of the two gaps:

side = min(maxHorizontalGap, maxVerticalGap)
area = side * side

Algorithm

  1. Sort each array (hBars, vBars).
  2. Scan the sorted array once to compute the length of the longest run of consecutive numbers.
  3. Return longestRun + 1 as the maximum gap for that direction.
  4. Compute the side length as the minimum of the two gaps and square it.

Pseudocode

function getMaxGap(bars):
    sort(bars)
    maxRun = 1
    curRun = 1
    for i from 1 to bars.length-1:
        if bars[i] == bars[i-1] + 1:
            curRun += 1
        else:
            curRun = 1
        maxRun = max(maxRun, curRun)
    return maxRun + 1   // gap width

function maximizeSquareHoleArea(n, m, hBars, vBars):
    side = min(getMaxGap(hBars), getMaxGap(vBars))
    return side * side

Complexity Analysis

  • Sorting each array: O(k log k) where k is the size of the array.
  • Linear scan: O(k).

Overall time complexity: O(n log n + m log m).
Space complexity: O(1) extra (in‑place sorting).

Reference Implementations

C++

class Solution {
public:
    int maximizeSquareHoleArea(int n, int m, std::vector<int>& hBars, std::vector<int>& vBars) {
        int side = std::min(getMaxGap(hBars), getMaxGap(vBars));
        return side * side;
    }

private:
    int getMaxGap(std::vector<int>& bars) {
        if (bars.empty()) return 1;          // no removable bars → gap of 1
        std::sort(bars.begin(), bars.end());

        int max_consecutive = 1;
        int current_consecutive = 1;

        for (size_t i = 1; i < bars.size(); ++i) {
            if (bars[i] == bars[i-1] + 1) {
                ++current_consecutive;
            } else {
                current_consecutive = 1;
            }
            max_consecutive = std::max(max_consecutive, current_consecutive);
        }
        return max_consecutive + 1;
    }
};

Python

def get_max_gap(bars: list[int]) -> int:
    if not bars:
        return 1
    bars.sort()
    max_consecutive = 1
    cur = 1
    for i in range(1, len(bars)):
        if bars[i] == bars[i - 1] + 1:
            cur += 1
        else:
            cur = 1
        max_consecutive = max(max_consecutive, cur)
    return max_consecutive + 1

def maximizeSquareHoleArea(n: int, m: int, hBars: list[int], vBars: list[int]) -> int:
    side = min(get_max_gap(hBars), get_max_gap(vBars))
    return side * side

JavaScript

/**
 * @param {number} n
 * @param {number} m
 * @param {number[]} hBars
 * @param {number[]} vBars
 * @return {number}
 */
var maximizeSquareHoleArea = function (n, m, hBars, vBars) {
    const getMaxGap = (bars) => {
        if (bars.length === 0) return 1;
        bars.sort((a, b) => a - b);
        let maxConsecutive = 1;
        let cur = 1;
        for (let i = 1; i < bars.length; i++) {
            if (bars[i] === bars[i - 1] + 1) {
                cur++;
            } else {
                cur = 1;
            }
            maxConsecutive = Math.max(maxConsecutive, cur);
        }
        return maxConsecutive + 1;
    };

    const side = Math.min(getMaxGap(hBars), getMaxGap(vBars));
    return side * side;
};

Additional Remarks

  • Sorting for contiguity: Sorting reduces the problem to a single linear pass, giving an overall O(k log k) time.
  • Fencepost consideration: k bars separate k + 1 spaces; removing them merges those spaces.
  • Bottleneck principle: In any square‑shaped constraint, the smaller dimension determines the final size.

This approach turns a 2‑D grid problem into two simple 1‑D scans, a technique often useful in resource allocation, window management, and other real‑world engineering scenarios.

Back to Blog

Related posts

Read more »