Solution 1
- TimeO(m log m + n log n)
- SpaceO(1)
Where, m is number of horizontal bars, n is number of vertical bars.
The key insight is that we can only make a square hole of side S, if there are at least S-1 consecutive horizontal bars and S-1 consecutive vertical bars.
So problem gets reduced to finding maximum consecutive streak in both horizontal and vertical bars.
Sort the bars and find maximum consecutive difference.
The side value is minimum of ( maximum consecutive horizontal and vertical gaps ) + 1.
Square the side value to get maximum area.
Python · 2026-01-15
class Solution:
'''
Time Complexity: O(m log m + n log n)
Space Complexity: O(1)
Where, m is number of horizontal bars, n is number of vertical bars.
The key insight is that we can only make a square hole of side S,
if there are at least S-1 consecutive horizontal bars and S-1 consecutive vertical bars.
So problem gets reduced to finding maximum consecutive streak in both horizontal and vertical bars.
Sort the bars and find maximum consecutive difference.
The side value is minimum of ( maximum consecutive horizontal and vertical gaps ) + 1.
Square the side value to get maximum area.
'''
def maximizeSquareHoleArea(self, n: int, m: int, hBars: List[int], vBars: List[int]) -> int:
def max_gap(bars):
bars.sort()
max_streak = 1
curr = 1
for i in range(1, len(bars)):
if bars[i] == bars[i - 1] + 1:
curr += 1
else:
curr = 1
max_streak = max(max_streak, curr)
# gap size = consecutive bars + 1
return max_streak + 1
max_h = max_gap(hBars)
max_v = max_gap(vBars)
side = min(max_h, max_v)
return side * side