Maximize Area of Square Hole in Grid - Problem

You are given two integers n and m representing a grid with n + 2 horizontal and m + 2 vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from 1.

You are also given two integer arrays hBars and vBars representing the bars that can be removed from horizontal and vertical bars respectively. Note that other bars are fixed and cannot be removed.

Return an integer denoting the maximum area of a square-shaped hole that can be created in the grid after removing some bars (possibly none).

Input & Output

Example 1 — Basic Grid
$ Input: n = 2, m = 3, hBars = [2, 3], vBars = [2, 4]
Output: 4
💡 Note: Remove horizontal bars 2,3 and vertical bars 2,4 to create a 2×2 square hole with area 4.
Example 2 — Small Grid
$ Input: n = 1, m = 1, hBars = [2], vBars = [2]
Output: 4
💡 Note: Remove both removable bars to create a 2×2 square hole.
Example 3 — No Removable Bars
$ Input: n = 2, m = 2, hBars = [], vBars = []
Output: 1
💡 Note: Cannot remove any bars, so maximum hole is 1×1 with area 1.

Constraints

  • 1 ≤ n, m ≤ 100
  • 1 ≤ hBars.length, vBars.length ≤ n+1, m+1
  • 1 ≤ hBars[i] ≤ n+1
  • 1 ≤ vBars[i] ≤ m+1

Visualization

Tap to expand
Maximize Area of Square Hole in Grid INPUT Grid: (n+2) x (m+2) = 4 x 5 bars h1 h2 h3 h4 v1 v2 v3 v4 v5 Fixed bar Removable Input Values: n = 2 m = 3 hBars=[2,3] vBars=[2,4] ALGORITHM STEPS 1 Sort removable bars hBars: [2,3], vBars: [2,4] 2 Find consecutive sequences hBars: 2,3 are consecutive vBars: 2,4 not consecutive 3 Calculate max gaps maxH = len(2,3) + 1 = 3 maxV = len(2) + 1 = 2 maxV = len(4) + 1 = 2 Consecutive Check: h: [2,3] --> diff=1 --> consecutive v: [2,4] --> diff=2 --> separate 4 Compute square area side = min(maxH, maxV) area = side * side FINAL RESULT Grid after removing bars: 2x2 2 units 2 Calculation: side = min(3, 2) = 2 area = 2 * 2 = 4 OUTPUT 4 Key Insight: The maximum square hole is determined by finding the longest consecutive sequences of removable bars. Each consecutive sequence of k removable bars creates a gap of (k+1) unit cells. The square side = min(maxHorizontalGap, maxVerticalGap), and area = side^2. TutorialsPoint - Maximize Area of Square Hole in Grid | Optimized - Find Longest Consecutive Sequences
Asked in
Google 15 Microsoft 12 Amazon 8
8.8K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen