Maximum Point Coverage by a Bounded-Perimeter Rectangle

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Given a list of 2D points points on the integer grid and a non-negative integer perimeter budget P, compute the largest number of input points that can be enclosed simultaneously by a single axis-aligned rectangle of perimeter at most P.

def maximum_covered_points(points: List[List[int]], P: int) -> int:
    pass

Geometric rules and conventions:

  • The rectangle's edges must be parallel to the x- and y-axes, though its corner coordinates may be arbitrary real numbers (they do not have to be integers).
  • Let width >= 0 and height >= 0 denote its horizontal and vertical side lengths; a rectangle is valid whenever 2 * (width + height) <= P.
  • Degenerate rectangles where width == 0, height == 0, or both (0 x 0 single point) are explicitly permitted.
  • Any point lying strictly inside the rectangle or anywhere along its four edges or corners counts as covered.
  • Duplicate coordinates in points represent distinct items and are counted individually whenever covered.
  • When points is empty, return 0.

Examples

Example 1

Input: points = [[1, 2], [4, 2], [1, 4], [3, 3], [4, 4], [12, 9]], P = 10
Output: 5

Placing the 3 x 2 rectangle [1, 4] x [2, 4] uses perimeter 2 * (3 + 2) = 10 <= 10 and covers the first five points ([1, 2], [4, 2], [1, 4], [3, 3], and [4, 4]), leaving only the distant point [12, 9] outside.

Example 2

Input: points = [[-2, 5], [3, 5], [-2, 5], [-2, 5], [0, 0]], P = 0
Output: 3

With P = 0, both width and height must be 0. Placing a 0 x 0 degenerate rectangle directly at (-2, 5) covers all three occurrences of [-2, 5].

Example 3

Input: points = [[0, 1], [2, 1], [5, 1]], P = 7
Output: 2

All three collinear points would require width 5 and height 0 (perimeter 10 > 7). A zero-height segment covering [0, 1] and [2, 1] needs perimeter 2 * (2 + 0) = 4 <= 7 (or [2, 1] and [5, 1] with perimeter 6 <= 7), covering 2 points.

Constraints

  • 0 <= len(points) <= 200
  • Each element of points is [x, y] with integers -1,000,000 <= x, y <= 1,000,000
  • 0 <= P <= 1,000,000,000

Step-by-step walkthrough

  1. Understand the geometry rules

    We receive up to 200 2D integer points [x, y] and an integer perimeter cap P. Our goal is to position one axis-aligned rectangle (a rectangle whose four sides run parallel to the horizontal and vertical axes) to enclose as many input points as possible:

    • Width w >= 0 and height h >= 0 may be any real numbers obeying 2 * (w + h) <= P.
    • Degenerate rectangles (w = 0 or h = 0) are permitted — so a flat line segment or a 0 x 0 single point counts as a valid rectangle.
    • Boundary coverage: Points sitting directly on an edge or corner count as covered.
    • Duplicates count individually: Covering three copies of [-2, 5] adds 3 to our score.
    • If points is empty, return 0.
  2. Shrink any valid rectangle to an integer bounding box

    Allowing floating-point coordinates and continuous widths/heights makes it look as if infinitely many rectangles must be checked. One geometric observation eliminates floating-point numbers completely!

    Suppose some valid rectangle covers a non-empty subset S of the input points. Pull its left, right, bottom, and top edges inward until each edge touches the outermost point(s) in S:

      Loose real-valued rectangle               Shrunk integer bounding box of S
      x in [0.6, 4.3], y in [1.8, 4.4]          x in [1, 4], y in [2, 4]
      +--------------------------+
      |   (1,4)*        *(4,4)   |              (1,4)*----------*(4,4)   height H = 2
      |          *(3,3)          |   shrinks     |      *(3,3)  |
      |   (1,2)*        *(4,2)   |   ------>    (1,2)*----------*(4,2)
      +--------------------------+                      width W = 3
      2 * (3.7 + 2.6) = 12.6                    2 * (3 + 2) = 10  (smaller or equal!)
    

    Shrinking never drops any point of S, and it only reduces (or leaves unchanged) the width and height! That establishes two simplifications: 1. Integer edges only: We only need to consider rectangles whose left and right sides lie on input x-coordinates, and whose bottom and top sides lie on input y-coordinates. 2. Integer half-perimeter budget: Because every input point has integer coordinates, the shrunk width W = right_x - left_x and height H = top_y - bottom_y are non-negative integers: - 2 * (W + H) <= P holds if and only if W + H <= P / 2. - Since W + H is an integer, W + H <= P / 2 is 100% equivalent to W + H <= P // 2! (For instance, when P = 7, P / 2 = 3.5, and the largest integer <= 3.5 is 7 // 2 = 3.)

  3. Why checking all 4-edge boxes is too slow

    Picking left, right, bottom, and top edges independently produces O(N^4) candidate boxes, and counting covered points per box costs O(N). At N = 200, 200^5 = 3.2 * 10^11 operations — thousands of times too slow!

    Instead of choosing all 4 edges up front, what happens when we lock only the left and right edges first?

  4. Key idea: fix the vertical strip, then slide a 1D window on `y`

    Once we choose left_x and right_x (left_x <= right_x), the horizontal width is fixed at width = right_x - left_x. If width > P // 2, this strip already exceeds our budget. Otherwise, our rectangle can spend up to max_height = (P // 2) - width vertically.

    Discard every point outside [left_x, right_x] and project the remaining points onto the y-axis! Our 2D problem has reduced to a 1D question: given a sorted list sorted_ys, what is the maximum number of values that fit inside [bottom_y, bottom_y + max_height]?

    Fix strip [left_x = 1, right_x = 4] with half_perimeter = 6  ->  width = 3, max_height = 3
    
      sorted_ys inside strip:   [ 1,   2,   3,   5,   7 ]
                                  ^---------^               span = 3 - 1 = 2 <= 3  (3 points)
                                       ^---------^          span = 5 - 2 = 3 <= 3  (3 points)
                                            ^---------^     span = 7 - 3 = 4 >  3  (too tall -> advance bottom_idx!)
    

    We solve this 1D window scan in O(N) time with a two-pointer sliding window: sweep top_idx across sorted_ys, and whenever sorted_ys[top_idx] - sorted_ys[bottom_idx] > max_height, increment bottom_idx. Because neither pointer ever moves backward, the entire pass runs in O(len(sorted_ys)) time!

    def max_points_in_y_window(sorted_ys: List[int], max_height: int) -> int:
        """Return the most values in sorted_ys that fit inside [y, y + max_height]."""
        best_count = 0
        bottom_idx = 0
    
        for top_idx in range(len(sorted_ys)):
            # Use strict '>' because points on the boundary (distance == max_height)
            # are still covered by the rectangle.
            while sorted_ys[top_idx] - sorted_ys[bottom_idx] > max_height:
                bottom_idx += 1
    
            window_count = top_idx - bottom_idx + 1
            if window_count > best_count:
                best_count = window_count
    
        return best_count
    
  5. Grow each vertical strip one column at a time

    First, group all points by x-coordinate into ys_by_x[x] (retaining duplicates!) and sort the distinct x-coordinates into unique_xs.

    For each left column left_idx, start with an empty sorted list strip_ys = [] and sweep right_idx rightward from left_idx: 1. Compute width = right_x - left_x. As soon as width > half_perimeter, break early — moving right_idx further right only makes width larger! 2. Insert each y in the newly added column ys_by_x[right_x] into strip_ys with bisect.insort(strip_ys, y) so strip_ys stays sorted without re-sorting from scratch. Across one left_idx, each of the N points is inserted at most once (O(N^2) total list-shift work per left_idx). 3. Call max_points_in_y_window(strip_ys, half_perimeter - width) and update best_total.

        half_perimeter = P // 2
    
        # ys_by_x: maps each x-coordinate -> list of y-coordinates in that vertical column
        # (preserving duplicates because repeated points count separately), e.g. {1: [2, 4]}.
        ys_by_x: Dict[int, List[int]] = {}
        for x, y in points:
            if x not in ys_by_x:
                ys_by_x[x] = []
            ys_by_x[x].append(y)
    
        # unique_xs: sorted distinct x-coordinates used as candidate left/right edges
        unique_xs = sorted(ys_by_x.keys())
        best_total = 0
    
        # Phase 2: Enumerate every valid vertical strip [left_x, right_x].
        for left_idx in range(len(unique_xs)):
            left_x = unique_xs[left_idx]
            # strip_ys: sorted list of all y-coordinates of points with left_x <= x <= right_x
            strip_ys: List[int] = []
    
            for right_idx in range(left_idx, len(unique_xs)):
                right_x = unique_xs[right_idx]
                width = right_x - left_x
    
                # Once width exceeds half_perimeter, moving right_idx further right only
                # increases width, so we can stop expanding this left_x early.
                if width > half_perimeter:
                    break
    
                # Insert the newly added column's y-values into strip_ys in sorted order.
                for y in ys_by_x[right_x]:
                    insort(strip_ys, y)
    
                # Phase 3: Spend the remaining perimeter budget on vertical height.
                max_height = half_perimeter - width
                covered = max_points_in_y_window(strip_ys, max_height)
                if covered > best_total:
                    best_total = covered
    
  6. Trace Example 1 step by step

    Let's trace points = [[1, 2], [4, 2], [1, 4], [3, 3], [4, 4], [12, 9]] with P = 10: - half_perimeter = 10 // 2 = 5 - ys_by_x = {1: [2, 4], 3: [3], 4: [2, 4], 12: [9]}, unique_xs = [1, 3, 4, 12]

    left_x  right_x  width  max_height  strip_ys         best y-window  best_total
    ------  -------  -----  ----------  ---------------  -------------  ----------
    1       1        0      5           [2, 4]           2 (span 2<=5)  2
    1       3        2      3           [2, 3, 4]        3 (span 2<=3)  3
    1       4        3      2           [2, 2, 3, 4, 4]  5 (span 2<=2)  5
    1       12       11     width 11 > 5 -> break!
    3       3        0      5           [3]              1 (span 0<=5)  5
    3       4        1      4           [2, 3, 4]        3 (span 2<=4)  5
    3       12       9      width 9 > 5  -> break!
    4       4        0      5           [2, 4]           2 (span 2<=5)  5
    4       12       8      width 8 > 5  -> break!
    12      12       0      5           [9]              1 (span 0<=5)  5
    

    The algorithm returns 5, achieved by the 3 x 2 rectangle [1, 4] x [2, 4] of perimeter 2 * (3 + 2) = 10.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from bisect import insort
    
    
    def max_points_in_y_window(sorted_ys: List[int], max_height: int) -> int:
        """Return the most values in sorted_ys that fit inside [y, y + max_height]."""
        best_count = 0
        bottom_idx = 0
    
        for top_idx in range(len(sorted_ys)):
            # Use strict '>' because points on the boundary (distance == max_height)
            # are still covered by the rectangle.
            while sorted_ys[top_idx] - sorted_ys[bottom_idx] > max_height:
                bottom_idx += 1
    
            window_count = top_idx - bottom_idx + 1
            if window_count > best_count:
                best_count = window_count
    
        return best_count
    
    
    def maximum_covered_points(points: List[List[int]], P: int) -> int:
        if not points:
            return 0
    
        # Phase 1: Shrinking any valid rectangle tightly around the integer points it
        # covers gives an integer width W and integer height H with 2 * (W + H) <= P.
        # Because W + H is an integer, W + H <= P / 2 is identical to W + H <= P // 2.
        half_perimeter = P // 2
    
        # ys_by_x: maps each x-coordinate -> list of y-coordinates in that vertical column
        # (preserving duplicates because repeated points count separately), e.g. {1: [2, 4]}.
        ys_by_x: Dict[int, List[int]] = {}
        for x, y in points:
            if x not in ys_by_x:
                ys_by_x[x] = []
            ys_by_x[x].append(y)
    
        # unique_xs: sorted distinct x-coordinates used as candidate left/right edges
        unique_xs = sorted(ys_by_x.keys())
        best_total = 0
    
        # Phase 2: Enumerate every valid vertical strip [left_x, right_x].
        for left_idx in range(len(unique_xs)):
            left_x = unique_xs[left_idx]
            # strip_ys: sorted list of all y-coordinates of points with left_x <= x <= right_x
            strip_ys: List[int] = []
    
            for right_idx in range(left_idx, len(unique_xs)):
                right_x = unique_xs[right_idx]
                width = right_x - left_x
    
                # Once width exceeds half_perimeter, moving right_idx further right only
                # increases width, so we can stop expanding this left_x early.
                if width > half_perimeter:
                    break
    
                # Insert the newly added column's y-values into strip_ys in sorted order.
                for y in ys_by_x[right_x]:
                    insort(strip_ys, y)
    
                # Phase 3: Spend the remaining perimeter budget on vertical height.
                max_height = half_perimeter - width
                covered = max_points_in_y_window(strip_ys, max_height)
                if covered > best_total:
                    best_total = covered
    
        return best_total
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine forming a rectangular picture frame out of a loop of string of total length P: the wider you pull the frame horizontally, the less string remains for its vertical height (width + height <= P / 2). First, notice that any valid axis-aligned rectangle (a rectangle whose sides run parallel to the x and y axes, including degenerate rectangles whose width or height is 0) can be shrunk tightly around the integer points it covers until its four sides touch those points — forming an integer bounding box (the smallest [min_x, max_x] x [min_y, max_y] box containing a set of points) without losing a single covered point! Second, once you lock the left and right edges to two vertical columns left_x and right_x, the horizontal width W = right_x - left_x is fixed, so the remaining problem reduces to a 1D two-pointer sliding window (a linear scan using two indices bottom_idx and top_idx that only step forward across a sorted array) to find the most y-coordinates inside that vertical strip that fit within height (P // 2) - W.

Why do more obvious ideas fail or time out? Testing all O(N^4) combinations of (left_x, right_x, bottom_y, top_y) and scanning N points per box takes O(N^5) time — roughly 3.2 * 10^11 steps for N = 200. On the other hand, trying to speed up the search by placing the rectangle's bottom-left corner directly onto an input point gives wrong answers: for the four diamond points (0, 1), (1, 0), (2, 1), (1, 2) with P = 8, the winning 2 x 2 box [0, 2] x [0, 2] has (0, 0) as its bottom-left corner, which is not one of the input points!

Let's walk through Example 1 (points = [[1, 2], [4, 2], [1, 4], [3, 3], [4, 4], [12, 9]], P = 10, so half_perimeter = 10 // 2 = 5):

Columns grouped by x:  x=1 -> [2, 4],  x=3 -> [3],  x=4 -> [2, 4],  x=12 -> [9]

1. Strip [1, 1]: width = 0, max_height = 5 - 0 = 5
   strip_ys = [2, 4]            -> span 4 - 2 = 2 <= 5 -> covers 2 points
2. Strip [1, 3]: width = 2, max_height = 5 - 2 = 3
   strip_ys = [2, 3, 4]         -> span 4 - 2 = 2 <= 3 -> covers 3 points
3. Strip [1, 4]: width = 3, max_height = 5 - 3 = 2
   strip_ys = [2, 2, 3, 4, 4]   -> span 4 - 2 = 2 <= 2 -> covers 5 points!
4. Strip [1, 12]: width = 11 > 5 -> break early!
5. Strips starting at x=3, 4, 12 hold at most 3, 2, 1 points -> answer is 5

Complexity

Let N be len(points) (N <= 200) and U be the number of distinct x-coordinates (U <= N).

  • Time: O(N^3). Grouping points by x and sorting unique_xs takes O(N log N). For each of the U choices of left_idx, as right_idx advances across at most U columns:
    1. Each of the N points is inserted into strip_ys at most once via bisect.insort (a standard-library helper that binary-searches the insertion spot in O(log N) and shifts list elements in O(N)), costing O(N^2) total across the inner loop for one left_idx.
    2. Each strip runs max_points_in_y_window in O(len(strip_ys)) = O(N) time, costing O(U * N) = O(N^2) across the inner loop for one left_idx. Summing O(N^2) work across U <= N choices of left_idx gives O(N^3) total time (at most ~1.35 * 10^6 inner window steps when N = 200, finishing in milliseconds).
  • Space: O(N). The dictionary ys_by_x, sorted list unique_xs, and active list strip_ys each store at most N integers at any time.

Edge cases

  • Empty input (points = []): Returns 0 immediately via the guard at the top of maximum_covered_points.
  • Zero or tiny perimeter (P = 0 or P = 1): half_perimeter = P // 2 = 0, allowing only 0 x 0 single-coordinate boxes; still covers 1 point when all points are distinct, or k points if k duplicates share the exact same (x, y) (Example 2).
  • Odd perimeter P (e.g., P = 7 in Example 3): Because bounding-box widths and heights of integer points are integers, 2 * (W + H) is always even, so P = 7 permits at most 2 * (W + H) = 6, i.e., W + H <= 7 // 2 = 3.
  • Collinear points (points lying on the same horizontal or vertical line): Covered cleanly because width == 0 (left_idx == right_idx) or max_height == 0 (width == half_perimeter) are naturally included.
  • Duplicate points ([[-2, 5], [-2, 5], [-2, 5]]): Appending every point's y into ys_by_x[x] rather than using a set ensures duplicates appear multiple times inside strip_ys and all count toward window_count.
  • Optimal box has no input point at any corner: Handled automatically because left_x and right_x come from one pair of points while bottom_y and top_y come independently from points inside strip_ys.

Common mistakes

  • Anchoring the bottom-left corner of the rectangle on an input point: Fails on diamond-shaped point sets like [[0, 1], [1, 0], [2, 1], [1, 2]] with P = 8, returning 3 instead of 4.
  • Rounding P / 2 upward ((P + 1) // 2): Falsely allows W + H = 2 (perimeter 4) when P = 3, covering both (0, 0) and (1, 1) when no rectangle of perimeter <= 3 can reach across a 1 x 1 diagonal.
  • Using >= instead of strict > in while sorted_ys[top_idx] - sorted_ys[bottom_idx] > max_height: Evicts points sitting right on the top/bottom boundary of the rectangle (distance == max_height), violating boundary inclusion.
  • Deduplicating points with set(map(tuple, points)): Undercounts repeated coordinates that must be counted separately.
  • Starting right_idx at left_idx + 1 instead of left_idx: Misses width == 0 vertical line segments and fails on inputs where all points share a single x-coordinate!

Alternative approaches

  • Pre-sort all points by y once instead of calling bisect.insort: Sort points by y once in O(N log N) before the loops; then for each (left_x, right_x) pair, filter [y for x, y in points_sorted_by_y if left_x <= x <= right_x] in O(N) to obtain strip_ys already sorted! Same O(N^3) worst-case complexity, though incremental insort + if width > half_perimeter: break skips scanning points outside narrow strips and breaks early when P is small.
  • Re-sort strip_ys from scratch on every right_idx: Costs O(N^3 log N), which still passes for N <= 200 in Python, though maintaining strip_ys incrementally saves the log N factor cleanly.

Follow-up questions

  • Does the maximum point count change if the rectangle's perimeter must equal P exactly rather than at most P? Not at all — the optimal count stays identical! Whenever a valid rectangle of width w and height h satisfies 2 * (w + h) < P, you can stretch its right edge further right by (P / 2) - (w + h) without uncovering any previously enclosed point, turning any <= P rectangle into an exact-perimeter P rectangle covering at least as many points.
  • How would you modify the solution if boundary points were excluded and only strictly interior points counted? A subset of integer points fits strictly inside an open real-valued rectangle of perimeter <= P if and only if its integer bounding box satisfies 2 * (W + H) < P (because any positive slack epsilon > 0 lets you expand each of the four sides outward by epsilon / 8 so every boundary point becomes strictly interior!). Since 2 * (W + H) is an even integer, 2 * (W + H) < P is equivalent to W + H <= (P - 1) // 2: return 0 immediately when P == 0 (a zero-perimeter box has empty interior), and otherwise set half_perimeter = (P - 1) // 2 and run the exact same strip-and-window scan!
  • If the input contained up to 100,000 points instead of 200, what algorithmic tools could avoid an O(N^3) scan? At N = 10^5, O(N^3) times out. For any single fixed box size W x H, a plane-sweep algorithm finds the maximum point coverage in O(N log N) time using coordinate compression (mapping the N distinct y-values onto dense indices 0..N-1) paired with a lazy segment tree (a binary tree over an array supporting O(log N) range +1/-1 updates and global-maximum queries as an x-window of width W slides left to right). When W + H <= P // 2 lets W vary and P // 2 is modest (e.g., <= 50), running one O(N log N) sweep per integer width W in 0..(P // 2) achieves O(P * N log N) time; if both N and P are huge, no sub-quadratic exact worst-case algorithm is known, so clarifying parameter regimes with the interviewer is essential.

Follow-up questions

Similar questions

More American interview questions

All 5 American questions →