Maximum Square Area by Removing Fences From a Field - Problem

There is a large (m - 1) x (n - 1) rectangular field with corners at (1, 1) and (m, n) containing some horizontal and vertical fences given in arrays hFences and vFences respectively.

Horizontal fences are from the coordinates (hFences[i], 1) to (hFences[i], n) and vertical fences are from the coordinates (1, vFences[i]) to (m, vFences[i]).

Return the maximum area of a square field that can be formed by removing some fences (possibly none) or -1 if it is impossible to make a square field.

Since the answer may be large, return it modulo 109 + 7.

Note: The field is surrounded by two horizontal fences from the coordinates (1, 1) to (1, n) and (m, 1) to (m, n) and two vertical fences from the coordinates (1, 1) to (m, 1) and (1, n) to (m, n). These boundary fences cannot be removed.

Input & Output

Example 1 — Basic Square Formation
$ Input: m = 4, n = 3, hFences = [2, 3], vFences = [2]
Output: 4
💡 Note: We have a 3×2 field with horizontal fences at rows 2,3 and vertical fence at column 2. We can form a 2×2 square by removing some fences, giving area = 2² = 4.
Example 2 — No Square Possible
$ Input: m = 6, n = 7, hFences = [2], vFences = [4]
Output: -1
💡 Note: The field is 5×6 with one horizontal fence at row 2 and one vertical fence at column 4. No valid square can be formed, so return -1.
Example 3 — Large Square
$ Input: m = 5, n = 5, hFences = [], vFences = []
Output: 16
💡 Note: Empty 4×4 field with no internal fences. The largest square is 4×4 with area = 16.

Constraints

  • 3 ≤ m, n ≤ 109
  • 1 ≤ hFences.length, vFences.length ≤ 1000
  • 1 < hFences[i] < m
  • 1 < vFences[i] < n
  • hFences and vFences are in strictly increasing order

Visualization

Tap to expand
Maximum Square Area by Removing Fences From a FieldOriginal Field4×3 with fencesvFences=[2]hFences=[2,3]⬇ Gap Analysis ⬇H-gaps: [1,1,1] V-gaps: [2,1]Common gap size: 1Maximum Square2×2Area = 4After removing fencesInput: m=4, n=3, hFences=[2,3], vFences=[2]Output: 4Maximum square area modulo 10^9 + 7
Understanding the Visualization
1
Input Field
Rectangular field with horizontal and vertical fences
2
Gap Analysis
Calculate gaps between consecutive fences
3
Square Formation
Find maximum matching gap for square
Key Takeaway
🎯 Key Insight: The maximum square size equals the largest gap that appears in both horizontal and vertical directions between consecutive fences
Asked in
Google 15 Meta 12 Amazon 8
8.9K Views
Medium Frequency
~35 min Avg. Time
245 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