Magicsheet logo

Maximum Square Area by Removing Fences From a Field

Medium
58.7%
Updated 6/1/2025

Asked by 1 Company

Maximum Square Area by Removing Fences From a Field

1. What is this problem about?

The Maximum Square Area by Removing Fences From a Field coding problem involves a large rectangular field with horizontal and vertical fences at specific coordinates. You can remove any number of fences to create a larger "cell." Your goal is to find the maximum possible area of a square field that can be formed by the remaining fences.

2. Why is this asked in interviews?

Atlassian uses this problem to test a candidate's ability to use Hash Tables for efficient lookups. The problem requires you to find a common "distance" that exists between both horizontal fences and vertical fences. It evaluates your skill in enumeration and your ability to handle large coordinates by focusing on the differences between them.

3. Algorithmic pattern used

This follows the Array, Hash Table, and Enumeration interview pattern.

  1. Calculate all possible distances between any two horizontal fences (including the field boundaries). Store these distances in a Hash Set.
  2. Calculate all possible distances between any two vertical fences.
  3. As you find a vertical distance, check if it exists in the horizontal Hash Set.
  4. The maximum such distance d that exists in both sets defines a d x d square. The answer is (modulo 10^9 + 7).

4. Example explanation

Field: 4x4. Horiz fences: [2]. Vert fences: [3]. Boundaries: H: [0, 2, 4], V: [0, 3, 4]. Horizontal distances:

  • 2-0 = 2
  • 4-2 = 2
  • 4-0 = 4 Set H: {2, 4}. Vertical distances:
  • 3-0 = 3
  • 4-3 = 1
  • 4-0 = 4 Checking V in Set H: 4 is in the set. Max square side is 4. Area = 16.

5. Common mistakes candidates make

The most common mistake is a brute-force approach that checks every combination of four fences, which is O(H² * V²) and too slow. Another error is forgetting to include the field's outer boundaries (0 and m/n) as "fences." Some candidates also fail to return -1 if no square (other than potentially the original fences) can be formed.

6. Interview preparation tip

For "Hash Table, Enumeration interview pattern" problems, think about what property needs to be "shared." Here, the square property requires width == height. By storing all possible heights and then checking all possible widths against them, you efficiently find the largest shared value.

Similar Questions