Taro Logo

Widest Possible Fence

Hard
Asked by:
Turing
6 views
Topics:
ArraysTwo Pointers

You are given an integer array planks, where planks[i] represents the height of the ith wooden plank. Each plank has a width of 1 unit.

You want to build a fence consisting of planks that all have the same height.

You may either use a plank as is, or combine exactly two distinct original planks into a single plank whose height equals the sum of their heights. Each original plank can be used at most once, and not all original planks need to be used.

Return the maximum possible width of the fence that can be built.

Example 1:

Input: planks = [1,3,2,5,7,5,4,2,1]

Output: 4

Explanation:

We can have four planks of height 5.

  • planks[3] = 5
  • planks[5] = 5
  • planks[0] + planks[6] = 1 + 4 = 5
  • planks[1] + planks[2] = 3 + 2 = 5

Hence, the maximum width is 4.

Example 2:

Input: planks = [2,3,7]

Output: 1

Explanation:

  • It is impossible to form two planks of the same height, even after combining two distinct original planks.
  • Since not all original planks need to be used, we can choose any one plank as the fence.
  • Therefore, the maximum possible width is 1.

Constraints:

  • 1 <= planks.length <= 1000
  • 1 <= planks[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are the grid boundaries `m` and `n` implicitly included as outer fences, meaning we always start with horizontal fences at 1 and `m` and vertical fences at 1 and `n`?
  2. Can `hFences` or `vFences` contain duplicate coordinates, and should we expect them to be provided in sorted order?
  3. If no valid enclosure can be formed after removing fences, should the function return -1 as specified in the description?
  4. Since the area can be very large, should we strictly return the maximum area modulo $10^9 + 7$, or should we also consider un-moduloed values for intermediate calculations?
  5. Does the grid dimensions `m` and `n` fit within standard 32-bit integer limits, or could they be large enough to cause overflow when calculating areas?

Brute Force Solution

Approach

Imagine you have a grid with several fence posts placed around, and you want to find the widest possible gap you can create between two opposite sides by removing some posts. The brute force approach works by systematically testing every single combination of removing posts to see what the resulting gap would be.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first pair of potential removal boundaries on opposite sides of the grid.
  2. Measure the distance of the gap created between those two boundaries.
  3. Check every single remaining fence post to see if any of them block this specific gap.
  4. If a post blocks the gap, write down that this particular combination does not work, and move on to the next set of boundaries.
  5. If no posts block the gap, save this gap size as a successful possibility.
  6. Repeat this testing process for every other possible pair of boundaries.
  7. After you have checked every single combination, look at all the successful gap sizes you found and pick the absolute biggest one.

Code Implementation

def widest_possible_fence(grid_width, grid_height, fence_posts_x, fence_posts_y):
    # Sort boundaries to test every sequential pair of fence posts as a gap
    sorted_x_coordinates = sorted([0] + fence_posts_x + [grid_width])
    sorted_y_coordinates = sorted([0] + fence_posts_y + [grid_height])

    maximum_found_width = 0
    maximum_found_height = 0

    for left_boundary_index in range(len(sorted_x_coordinates)):
        for right_boundary_index in range(left_boundary_index + 1, len(sorted_x_coordinates)):
            current_width_gap = sorted_x_coordinates[right_boundary_index] - sorted_x_coordinates[left_boundary_index]

            for bottom_boundary_index in range(len(sorted_y_coordinates)):
                for top_boundary_index in range(bottom_boundary_index + 1, len(sorted_y_coordinates)):
                    current_height_gap = sorted_y_coordinates[top_boundary_index] - sorted_y_coordinates[bottom_boundary_index]

                    # Check every fence post to ensure no obstructions exist within this specific gap
                    is_gap_obstructed = False

                    for post_x, post_y in zip(fence_posts_x, fence_posts_y):
                        if sorted_x_coordinates[left_boundary_index] < post_x < sorted_x_coordinates[right_boundary_index] and sorted_y_coordinates[bottom_boundary_index] < post_y < sorted_y_coordinates[top_boundary_index]:
                            is_gap_obstructed = True
                            break

                    # Track the largest unobstructed rectangular area found across all tested combinations
                    if not is_gap_obstructed:
                        current_area = current_width_gap * current_height_gap
                        maximum_possible_area = maximum_found_width * maximum_found_height

                        if current_area > maximum_possible_area:
                            maximum_found_width = current_width_gap
                            maximum_found_height = current_height_gap

    return maximum_found_width * maximum_found_height

Big(O) Analysis

Time Complexity
O(n^3) – The brute force approach systematically tests every pair of potential boundaries across the grid, which creates n squared boundary combinations. For each of these boundary pairs, we must check every single one of the n remaining fence posts to see if it blocks the gap. This results in nested checks proportional to the number of boundaries multiplied by the number of posts. Consequently, the total operations approximate n cubed over 2, which simplifies to a cubic time complexity of O(n^3).
Space Complexity
O(1) – The brute force algorithm only utilizes a few primitive integer variables to keep track of the current pair of boundaries, distances, and the maximum gap size found so far. It does not allocate any dynamic data structures, temporary lists, or recursive call stacks that scale with the input size. Therefore, the extra auxiliary memory required remains constant regardless of the number of fence posts or potential boundaries.

Optimal Solution

Approach

Instead of testing every single combination of gaps, the optimal approach focuses on finding the single largest gap in both dimensions independently. By looking at where the vertical and horizontal bars are placed, we can find the biggest empty space by simply sorting their positions and measuring the distances between neighboring pairs.

Here's how the algorithm would work step-by-step:

  1. Collect all the horizontal divider positions and all the vertical divider positions, and don't forget to include the outer boundaries of the area as extra dividers.
  2. Arrange the horizontal dividers in numerical order from smallest to largest.
  3. Measure the distance between every adjacent pair of horizontal dividers to find the largest vertical gap.
  4. Arrange the vertical dividers in numerical order from smallest to largest.
  5. Measure the distance between every adjacent pair of vertical dividers to find the largest horizontal gap.
  6. Multiply the largest vertical gap by the largest horizontal gap to find the total area of the widest possible empty space.
  7. By treating the horizontal and vertical directions separately, we avoid checking every single crossing and solve the problem very quickly.

Code Implementation

def widest_possible_fence(fence_height, fence_width, horizontal_bars, vertical_bars):
    
    # Outer boundaries must be included because they limit the maximum possible empty area.
    all_horizontal_bars = sorted([0, fence_height] + horizontal_bars)
    
    max_vertical_gap = max(all_horizontal_bars[index] - all_horizontal_bars[index - 1] for index in range(1, len(all_horizontal_bars)))
    
    # Outer boundaries are added here as well to correctly measure edge gaps.
    all_vertical_bars = sorted([0, fence_width] + vertical_bars)
    
    max_horizontal_gap = max(all_vertical_bars[index] - all_vertical_bars[index - 1] for index in range(1, len(all_vertical_bars)))
    
    # Independence of dimensions allows us to multiply max gaps directly for total area.
    return max_vertical_gap * max_horizontal_gap

Big(O) Analysis

Time Complexity
O(h log h + v log v) – The time complexity is driven by sorting the h horizontal divider positions and the v vertical divider positions. Sorting the horizontal dividers takes O(h log h) time, while sorting the vertical dividers takes O(v log v) time. Following the sorting steps, a single linear pass over each sorted list of size h and v is performed to find the maximum gaps. Combining these operations yields approximately h log h + v log v total operations, which simplifies to O(h log h + v log v).
Space Complexity
O(N) – To find the widest fence, we must collect all horizontal and vertical divider positions, including the outer boundaries, into temporary lists and sort them. Assuming N represents the total number of dividers across both dimensions, these auxiliary lists store up to N elements in memory. Therefore, the extra space required grows linearly with the input size, leading to a space complexity of O(N).

Edge Cases

Fences arrays do not include the grid boundaries m and n
How to Handle:
Explicitly append 1 and m to hFences, and 1 and n to vFences before processing to include the outer walls.
No common spacing can be formed between any horizontal and vertical fence pairs
How to Handle:
Return -1 if the intersection of possible horizontal and vertical differences is empty.
Duplicate fence coordinates provided in the input arrays
How to Handle:
Sort and deduplicate the fence arrays before generating differences to avoid redundant zero-width or zero-height intervals.
Maximum possible area exceeds standard integer limits before applying modulo
How to Handle:
Perform area multiplication using 64-bit integers and apply modulo 10^9 + 7 at the final return step.
Fences arrays contain only a single element
How to Handle:
Appending the grid boundaries ensures we always have at least two coordinates to compute valid fence gaps.
Grid dimensions m and n are at their maximum constraints
How to Handle:
O(N^2 + M^2) difference generation scales efficiently within time limits given typical constraint sizes.