Maximum Square Area by Removing Fences From a Field — LeetCode 2975 Python Solution

MediumArrayHash TableEnumeration
Problem
#2975
Pattern
Hash Map
Reading time
3 min

The 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]).

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(h^2 + v^2)
SpaceO(h^2 + v^2) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2975. Maximum Square Area by Removing Fences From a Field is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2975. Maximum Square Area by Removing Fences From a Field?
LeetCode 2975. Maximum Square Area by Removing Fences From a Field is rated Medium on LeetCode.
What is the time complexity of LeetCode 2975. Maximum Square Area by Removing Fences From a Field?
The Python solution on this page runs in O(h^2 + v^2).
What is the space complexity of LeetCode 2975. Maximum Square Area by Removing Fences From a Field?
The Python solution on this page uses O(h^2 + v^2) auxiliary space.
What topics does LeetCode 2975. Maximum Square Area by Removing Fences From a Field cover?
LeetCode 2975. Maximum Square Area by Removing Fences From a Field is tagged Array, Hash Table and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview