Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: The Skyline Problem

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "218" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]: lefti is the x coordinate of the left edge of the ith building. righti is the x coordinate of the right edge of the ith building. heighti is the height of the ith building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...] Example 1: Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] Explanation: Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. Example 2: Input: buildings = [[0,2,3],[2,5,3]] Output: [[0,3],[5,0]] Constraints: 1 <= buildings.length <= 104 0 <= lefti < righti <= 231 - 1 1 <= heighti <= 231 - 1 buildings is sorted by lefti in non-decreasing order.

Explanation

Here's a breakdown of the solution:

  • Sweep Line Algorithm: Process the buildings from left to right using a sweep line. At each x-coordinate, update a priority queue (max heap) to track the current heights of active buildings.
  • Height Tracking: The priority queue stores the heights of buildings that are currently "active" (i.e., the sweep line is within their x-range). We always keep track of the maximum height in the heap.
  • Skyline Point Generation: Whenever the maximum height in the heap changes, it signifies a key point in the skyline. We add this key point (x-coordinate, height) to our result, avoiding consecutive points with the same height.

  • Runtime Complexity: O(n log n), where n is the number of buildings due to the heap operations.

  • Storage Complexity: O(n) in the worst case to store the skyline points and the heap.

Code

    import heapq

def getSkyline(buildings):
    """
    Calculates the skyline of a set of buildings.

    Args:
        buildings: A list of lists, where each inner list represents a building
                   in the format [left, right, height].

    Returns:
        A list of lists, where each inner list represents a key point in the
        skyline in the format [x, y].
    """

    events = []
    for l, r, h in buildings:
        events.append((l, -h, r))  # Use negative height for max-heap
        events.append((r, 0, 0))   # Mark end of building

    events.sort()

    skyline = []
    heights = [(0, float('inf'))]  # Initialize with a ground level
    heapq.heapify(heights)
    active_buildings = {}

    for x, h, r in events:
        if h < 0:  # Start of building
            heapq.heappush(heights, (h, r))
            active_buildings[r] = active_buildings.get(r, 0) + 1
        else: # End of building
            active_buildings[x] = active_buildings.get(x,0) + 1


        # Clean up inactive buildings from the heap
        while heights and active_buildings.get(heights[0][1], 0) > 0:
            right_end = heapq.heappop(heights)[1]
            active_buildings[right_end] -= 1
            if active_buildings[right_end] == 0:
                del active_buildings[right_end]

        current_height = -heights[0][0]

        if not skyline or current_height != skyline[-1][1]:
            skyline.append([x, current_height])

    return skyline

More from this blog

C

Chatmagic blog

2894 posts