Taro Logo

Maximum Building Height

#1 Most AskedHard
0 views
Topics:
ArraysGreedy Algorithms

You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.

However, there are city restrictions on the heights of the new buildings:

  • The height of each building must be a non-negative integer.
  • The height of the first building must be 0.
  • The height difference between any two adjacent buildings cannot exceed 1.

Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.

It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.

Return the maximum possible height of the tallest building.

Example 1:

Input: n = 5, restrictions = [[2,1],[4,1]]
Output: 2
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.

Example 2:

Input: n = 6, restrictions = []
Output: 5
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.

Example 3:

Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]
Output: 5
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.

Constraints:

  • 2 <= n <= 109
  • 0 <= restrictions.length <= min(n - 1, 105)
  • 2 <= idi <= n
  • idi is unique.
  • 0 <= maxHeighti <= 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 building indices in the restrictions list guaranteed to be given in sorted order, or could they appear in arbitrary order?
  2. Is the first building (at index 1) strictly required to have a height of 0, or can its height be anything as long as the absolute height is 0?
  3. Can multiple restrictions be provided for the same building index in the input list, and if so, how should we handle conflicting height limits?
  4. Are the restrictions guaranteed to be valid and satisfiable, or should my solution handle cases where no valid building heights are possible?
  5. If the restrictions list is empty (aside from the implicit height limit of 0 at the first building), how should the maximum height be calculated up to building n?

Brute Force Solution

Approach

Imagine you need to build the tallest possible structures at specific locations while making sure no building is too much taller than its neighbor. The brute force approach involves trying every conceivable height for every single building and checking which combination works best.

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

  1. Start by looking at the specific locations where you are allowed to build taller structures.
  2. Guess a random height for the very first building to see what happens.
  3. Move to the next required building location and guess a random height for it, making sure it does not exceed the height limit set by its distance from the previous building.
  4. Continue this guessing game for all the other required building locations, one by one.
  5. Once you have assigned a height to every single required building, check if all the building height restrictions and neighbor difference rules are successfully satisfied.
  6. If the combination violates any of the height difference rules, throw it away and forget about it.
  7. If the combination is valid, look at the tallest building in this setup and compare it with the tallest one you found in previous valid tries.
  8. Repeat this entire process of guessing every possible height combination until you have explored every single option.
  9. Finally, pick the absolute tallest building height you encountered among all the successful combinations.

Code Implementation

def max_building_height(num_buildings, restrictions):
    # Sort restrictions by building index to properly evaluate neighbor differences
    sorted_restrictions = sorted(restrictions, key=lambda item: item[0])

    full_restrictions = [[1, 0]] + sorted_restrictions
    if full_restrictions[-1][0] < num_buildings:
        full_restrictions.append([num_buildings, num_buildings - 1])

    max_possible_height = 0

    # Recursively or iteratively generate all combinations to find the maximum possible valid height
    def evaluate_combinations(current_index, current_heights):
        nonlocal max_possible_height
        if current_index == len(full_restrictions):
            current_max = max(current_heights)
            if current_max > max_possible_height:
                max_possible_height = current_max
            return

        target_index, height_limit = full_restrictions[current_index]
        previous_index, previous_height = full_restrictions[current_index - 1] if current_index > 0 else [1, 0]
        max_jump = target_index - previous_index

        for assigned_height in range(height_limit + 1):
            if current_index == 0 or abs(assigned_height - previous_height) <= max_jump:
                evaluate_combinations(current_index + 1, current_heights + [assigned_height])

    # Kick off the exhaustive search starting from the first building restriction
    evaluate_combinations(0, [])

    return max_possible_height

Big(O) Analysis

Time Complexity
O(infinity) – The brute force approach requires trying every conceivable height for every single building location through exhaustive guessing. Because building heights can theoretically be any arbitrarily large number up to the maximum possible height limit, the number of combinations grows exponentially or infinitely depending on the domain of allowed heights. Exploring every single height combination for all building locations means the total operations grow without a fixed polynomial bound relative to the input size n. Thus, this naive guessing strategy cannot be bounded by a standard polynomial time complexity like O(n squared).
Space Complexity
O(k) – The algorithm requires sorting the given restriction list of length k, which uses auxiliary space on the call stack for the sorting algorithm. Additionally, we store a constant number of scalar variables to track the current height limits and the maximum height found so far. Therefore, the extra memory required scales linearly with the number of restrictions k rather than the total number of buildings n. As k grows, the auxiliary space used by the sorting routine dominates the memory footprint.

Optimal Solution

Approach

Instead of checking every single building one by one, the optimal approach first sorts the known height restrictions and adds the ground at the very beginning and the final building at the very end. Then, it makes two passes through the restrictions to figure out how much buildings are allowed to grow based on their neighbors.

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

  1. Add the starting point at ground level and include the very last destination as a restriction with a maximum possible height.
  2. Sort all the height restrictions from left to right so they are in order.
  3. Take a forward pass through the sorted restrictions, adjusting each maximum allowed height so that no building grows taller than its immediate left neighbor plus the distance between them.
  4. Take a backward pass through the restrictions, this time adjusting each maximum allowed height from right to left so that no building grows taller than its immediate right neighbor plus the distance between them.
  5. Now that every restriction has its final, safest upper limit, look at the space between every adjacent pair of restrictions.
  6. Calculate the absolute tallest a building could possibly stretch in the open gap between each pair of restrictions, keeping in mind that the height can only increase by one step for every single step moved horizontally.
  7. Keep track of the highest peak found during this process to determine the ultimate maximum building height.

Code Implementation

class Solution:
    def max_building(self, total_buildings: int, restrictions: list[list[int]]) -> int:
        restrictions.append([1, 0])
        restrictions.append([total_buildings, total_buildings - 1])
        restrictions.sort(key=lambda item: item[0])

        # Ensure left-to-right neighbor heights do not exceed slope limits.
        for index in range(1, len(restrictions)):
            previous_index = index - 1
            max_allowed_height = restrictions[previous_index][1] + (restrictions[index][0] - restrictions[previous_index][0])
            if restrictions[index][1] > max_allowed_height:
                restrictions[index][1] = max_allowed_height

        # Ensure right-to-left neighbor heights do not exceed slope limits.
        for index in range(len(restrictions) - 2, -1, -1):
            next_index = index + 1
            max_allowed_height = restrictions[next_index][1] + (restrictions[next_index][0] - restrictions[index][0])
            if restrictions[index][1] > max_allowed_height:
                restrictions[index][1] = max_allowed_height

        ultimate_maximum_height = 0

        # Evaluate peak heights achievable in open gaps between restrictions.
        for index in range(1, len(restrictions)):
            left_building = restrictions[index - 1]
            right_building = restrictions[index]
            horizontal_distance = right_building[0] - left_building[0]
            height_difference = abs(right_building[1] - left_building[1])
            peak_height = (horizontal_distance + left_building[1] + right_building[1]) // 2
            if peak_height > ultimate_maximum_height:
                ultimate_maximum_height = peak_height

        return ultimate_maximum_height

Big(O) Analysis

Time Complexity
O(m log m) – The time complexity is primarily driven by sorting the m height restrictions, which takes O(m log m) time where m is the number of restrictions. Following the sort, the forward and backward passes each iterate through the m sorted restrictions in linear time, O(m). Finally, checking the gaps between adjacent restrictions requires a single pass of O(m) operations. Since m log m dominates the linear passes, the total operations approximate m log m, which simplifies to O(m log m).
Space Complexity
O(K) – The auxiliary space is driven by the need to store the height restrictions, where K is the number of given restrictions in the input. When we insert the starting ground level and the final destination building into our restriction list, it grows to size K plus two. The sorting step and the forward and backward passes operate directly on this list or auxiliary structures of proportional size. Since no other major data structures are created, the total extra memory scales linearly with the number of restrictions.

Edge Cases

Restrictions list is empty
How to Handle:
Assume only the first building has a height of 0 and the last building n can reach n minus 1 by incrementing by 1 each step.
Restriction provided for building 1 with height greater than 0
How to Handle:
Clamp the height of building 1 to 0 since the problem explicitly states the heights must start at 0 for the first building.
Duplicate restrictions for the same building index
How to Handle:
Preprocess the restrictions by keeping only the minimum height restriction for any duplicate building index.
Restrictions do not cover the last building n
How to Handle:
Append a virtual restriction at building n with an effectively infinite height to bound the final slope.
Very large values of n up to 10 to the 9th power
How to Handle:
Sort only the given restrictions and iterate through them instead of allocating an array of size n to ensure optimal space and time efficiency.
Steep height restrictions that force adjacent buildings to drop faster than the slope of 1 allows
How to Handle:
Perform a two-pass left-to-right and right-to-left propagation to strictly enforce the maximum allowable height difference of 1 between adjacent buildings.
Extremely tall restrictions that exceed the distance between buildings
How to Handle:
Mathematical propagation naturally caps the peak height by the midpoint formula between adjacent restricted buildings.
0/2 completed