#2943
Maximize Area of Square Hole in Grid
MediumArraySortingSortingArray Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log m) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n + m log m)Space O(1)
By focusing on the gaps between the bars after sorting, we can efficiently find the maximum square area without checking every combination. This reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Sort the hBars and vBars arrays.
- 2Step 2: Calculate the maximum gaps between consecutive bars in both arrays, including the edges of the grid.
- 3Step 3: The maximum area of the square hole is the square of the minimum gap found.
solution.py11 lines
1def maxSquareAreaOptimal(n, m, hBars, vBars):
2 hBars.sort()
3 vBars.sort()
4 max_h_gap = max(hBars[0] - 1, n + 1 - hBars[-1])
5 for i in range(1, len(hBars)):
6 max_h_gap = max(max_h_gap, hBars[i] - hBars[i - 1])
7 max_v_gap = max(vBars[0] - 1, m + 1 - vBars[-1])
8 for i in range(1, len(vBars)):
9 max_v_gap = max(max_v_gap, vBars[i] - vBars[i - 1])
10 return min(max_h_gap, max_v_gap) ** 2
11ℹ
Complexity note: The sorting of the bars takes O(n log n) and O(m log m), while calculating the gaps is linear, leading to an overall efficient solution.
- 1Understanding the gaps between bars is crucial for determining the maximum square area.
- 2Sorting the bars allows us to efficiently calculate the maximum gaps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.