Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 fences cannot be removed.
Example 1:
Input: m = 4, n = 3, hFences = [2,3], vFences = [2] Output: 4 Explanation: Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4.
Example 2:
Input: m = 6, n = 7, hFences = [2], vFences = [4] Output: -1 Explanation: It can be proved that there is no way to create a square field by removing fences.
Constraints:
3 <= m, n <= 1091 <= hFences.length, vFences.length <= 6001 < hFences[i] < m1 < vFences[i] < nhFences and vFences are unique.Problem summary: 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 fences cannot be removed.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
4 3 [2,3] [2]
6 7 [2] [4]
maximize-area-of-square-hole-in-grid)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2975: Maximum Square Area by Removing Fences From a Field
class Solution {
public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) {
Set<Integer> hs = f(hFences, m);
Set<Integer> vs = f(vFences, n);
hs.retainAll(vs);
int ans = -1;
final int mod = (int) 1e9 + 7;
for (int x : hs) {
ans = Math.max(ans, x);
}
return ans > 0 ? (int) (1L * ans * ans % mod) : -1;
}
private Set<Integer> f(int[] nums, int k) {
int n = nums.length;
nums = Arrays.copyOf(nums, n + 2);
nums[n] = 1;
nums[n + 1] = k;
Arrays.sort(nums);
Set<Integer> s = new HashSet<>();
for (int i = 0; i < nums.length; ++i) {
for (int j = 0; j < i; ++j) {
s.add(nums[i] - nums[j]);
}
}
return s;
}
}
// Accepted solution for LeetCode #2975: Maximum Square Area by Removing Fences From a Field
func maximizeSquareArea(m int, n int, hFences []int, vFences []int) int {
f := func(nums []int, k int) map[int]bool {
nums = append(nums, 1, k)
sort.Ints(nums)
s := map[int]bool{}
for i := 0; i < len(nums); i++ {
for j := 0; j < i; j++ {
s[nums[i]-nums[j]] = true
}
}
return s
}
hs := f(hFences, m)
vs := f(vFences, n)
ans := 0
for h := range hs {
if vs[h] {
ans = max(ans, h)
}
}
if ans > 0 {
return ans * ans % (1e9 + 7)
}
return -1
}
# Accepted solution for LeetCode #2975: Maximum Square Area by Removing Fences From a Field
class Solution:
def maximizeSquareArea(
self, m: int, n: int, hFences: List[int], vFences: List[int]
) -> int:
def f(nums: List[int], k: int) -> Set[int]:
nums.extend([1, k])
nums.sort()
return {b - a for a, b in combinations(nums, 2)}
mod = 10**9 + 7
hs = f(hFences, m)
vs = f(vFences, n)
ans = max(hs & vs, default=0)
return ans**2 % mod if ans else -1
// Accepted solution for LeetCode #2975: Maximum Square Area by Removing Fences From a Field
use std::collections::HashSet;
impl Solution {
pub fn maximize_square_area(m: i32, n: i32, h_fences: Vec<i32>, v_fences: Vec<i32>) -> i32 {
fn calc(mut nums: Vec<i32>, k: i32) -> HashSet<i32> {
nums.push(k);
nums.push(1);
nums.sort_unstable();
let mut s = HashSet::new();
let len = nums.len();
for i in 0..len {
for j in 0..i {
s.insert(nums[i] - nums[j]);
}
}
s
}
let hs = calc(h_fences, m);
let vs = calc(v_fences, n);
let mut ans = 0i64;
for &h in hs.iter() {
if vs.contains(&h) {
ans = ans.max(h as i64);
}
}
if ans > 0 {
let modv = 1_000_000_007i64;
((ans * ans) % modv) as i32
} else {
-1
}
}
}
// Accepted solution for LeetCode #2975: Maximum Square Area by Removing Fences From a Field
function maximizeSquareArea(m: number, n: number, hFences: number[], vFences: number[]): number {
const f = (nums: number[], k: number): Set<number> => {
nums.push(1, k);
nums.sort((a, b) => a - b);
const s: Set<number> = new Set();
for (let i = 0; i < nums.length; ++i) {
for (let j = 0; j < i; ++j) {
s.add(nums[i] - nums[j]);
}
}
return s;
};
const hs = f(hFences, m);
const vs = f(vFences, n);
let ans = 0;
for (const h of hs) {
if (vs.has(h)) {
ans = Math.max(ans, h);
}
}
return ans ? Number(BigInt(ans) ** 2n % 1000000007n) : -1;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.