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- andy-axes, though its corner coordinates may be arbitrary real numbers (they do not have to be integers). - Let
width >= 0andheight >= 0denote its horizontal and vertical side lengths; a rectangle is valid whenever2 * (width + height) <= P. - Degenerate rectangles where
width == 0,height == 0, or both (0 x 0single 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
pointsrepresent distinct items and are counted individually whenever covered. - When
pointsis empty, return0.
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
pointsis[x, y]with integers-1,000,000 <= x, y <= 1,000,000 0 <= P <= 1,000,000,000
Step-by-step walkthrough
Understand the geometry rules
We receive up to
2002D integer points[x, y]and an integer perimeter capP. 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 >= 0and heighth >= 0may be any real numbers obeying2 * (w + h) <= P. - Degenerate rectangles (
w = 0orh = 0) are permitted — so a flat line segment or a0 x 0single 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]adds3to our score. - If
pointsis empty, return0.
- Width
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
Sof the input points. Pull its left, right, bottom, and top edges inward until each edge touches the outermost point(s) inS: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 inputx-coordinates, and whose bottom and top sides lie on inputy-coordinates. 2. Integer half-perimeter budget: Because every input point has integer coordinates, the shrunk widthW = right_x - left_xand heightH = top_y - bottom_yare non-negative integers: -2 * (W + H) <= Pholds if and only ifW + H <= P / 2. - SinceW + His an integer,W + H <= P / 2is 100% equivalent toW + H <= P // 2! (For instance, whenP = 7,P / 2 = 3.5, and the largest integer<= 3.5is7 // 2 = 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 costsO(N). AtN = 200,200^5 = 3.2 * 10^11operations — 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?
Key idea: fix the vertical strip, then slide a 1D window on `y`
Once we choose
left_xandright_x(left_x <= right_x), the horizontal width is fixed atwidth = right_x - left_x. Ifwidth > P // 2, this strip already exceeds our budget. Otherwise, our rectangle can spend up tomax_height = (P // 2) - widthvertically.Discard every point outside
[left_x, right_x]and project the remaining points onto they-axis! Our 2D problem has reduced to a 1D question: given a sorted listsorted_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: sweeptop_idxacrosssorted_ys, and wheneversorted_ys[top_idx] - sorted_ys[bottom_idx] > max_height, incrementbottom_idx. Because neither pointer ever moves backward, the entire pass runs inO(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_countGrow each vertical strip one column at a time
First, group all points by
x-coordinate intoys_by_x[x](retaining duplicates!) and sort the distinctx-coordinates intounique_xs.For each left column
left_idx, start with an empty sorted liststrip_ys = []and sweepright_idxrightward fromleft_idx: 1. Computewidth = right_x - left_x. As soon aswidth > half_perimeter, break early — movingright_idxfurther right only makeswidthlarger! 2. Insert eachyin the newly added columnys_by_x[right_x]intostrip_yswithbisect.insort(strip_ys, y)sostrip_ysstays sorted without re-sorting from scratch. Across oneleft_idx, each of theNpoints is inserted at most once (O(N^2)total list-shift work perleft_idx). 3. Callmax_points_in_y_window(strip_ys, half_perimeter - width)and updatebest_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 = coveredTrace Example 1 step by step
Let's trace
points = [[1, 2], [4, 2], [1, 4], [3, 3], [4, 4], [12, 9]]withP = 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) 5The algorithm returns
5, achieved by the3 x 2rectangle[1, 4] x [2, 4]of perimeter2 * (3 + 2) = 10.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 byxand sortingunique_xstakesO(N log N). For each of theUchoices ofleft_idx, asright_idxadvances across at mostUcolumns:- Each of the
Npoints is inserted intostrip_ysat most once viabisect.insort(a standard-library helper that binary-searches the insertion spot inO(log N)and shifts list elements inO(N)), costingO(N^2)total across the inner loop for oneleft_idx. - Each strip runs
max_points_in_y_windowinO(len(strip_ys)) = O(N)time, costingO(U * N) = O(N^2)across the inner loop for oneleft_idx. SummingO(N^2)work acrossU <= Nchoices ofleft_idxgivesO(N^3)total time (at most ~1.35 * 10^6inner window steps whenN = 200, finishing in milliseconds).
- Each of the
- Space:
O(N). The dictionaryys_by_x, sorted listunique_xs, and active liststrip_yseach store at mostNintegers at any time.
Edge cases
- Empty input (
points = []): Returns0immediately via the guard at the top ofmaximum_covered_points. - Zero or tiny perimeter (
P = 0orP = 1):half_perimeter = P // 2 = 0, allowing only0 x 0single-coordinate boxes; still covers1point when all points are distinct, orkpoints ifkduplicates share the exact same(x, y)(Example 2). - Odd perimeter
P(e.g.,P = 7in Example 3): Because bounding-box widths and heights of integer points are integers,2 * (W + H)is always even, soP = 7permits at most2 * (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) ormax_height == 0(width == half_perimeter) are naturally included. - Duplicate points (
[[-2, 5], [-2, 5], [-2, 5]]): Appending every point'syintoys_by_x[x]rather than using asetensures duplicates appear multiple times insidestrip_ysand all count towardwindow_count. - Optimal box has no input point at any corner: Handled automatically because
left_xandright_xcome from one pair of points whilebottom_yandtop_ycome independently from points insidestrip_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]]withP = 8, returning3instead of4. - Rounding
P / 2upward ((P + 1) // 2): Falsely allowsW + H = 2(perimeter4) whenP = 3, covering both(0, 0)and(1, 1)when no rectangle of perimeter<= 3can reach across a1 x 1diagonal. - Using
>=instead of strict>inwhile 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_idxatleft_idx + 1instead ofleft_idx: Misseswidth == 0vertical line segments and fails on inputs where all points share a singlex-coordinate!
Alternative approaches
- Pre-sort all points by
yonce instead of callingbisect.insort: Sortpointsbyyonce inO(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]inO(N)to obtainstrip_ysalready sorted! SameO(N^3)worst-case complexity, though incrementalinsort+if width > half_perimeter: breakskips scanning points outside narrow strips and breaks early whenPis small. - Re-sort
strip_ysfrom scratch on everyright_idx: CostsO(N^3 log N), which still passes forN <= 200in Python, though maintainingstrip_ysincrementally saves thelog Nfactor 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
wand heighthsatisfies2 * (w + h) < P, you can stretch its right edge further right by(P / 2) - (w + h)without uncovering any previously enclosed point, turning any<= Prectangle into an exact-perimeterPrectangle 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
<= Pif and only if its integer bounding box satisfies2 * (W + H) < P(because any positive slackepsilon > 0lets you expand each of the four sides outward byepsilon / 8so every boundary point becomes strictly interior!). Since2 * (W + H)is an even integer,2 * (W + H) < Pis equivalent toW + H <= (P - 1) // 2: return0immediately whenP == 0(a zero-perimeter box has empty interior), and otherwise sethalf_perimeter = (P - 1) // 2and 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 sizeW x H, a plane-sweep algorithm finds the maximum point coverage inO(N log N)time using coordinate compression (mapping theNdistincty-values onto dense indices0..N-1) paired with a lazy segment tree (a binary tree over an array supportingO(log N)range+1/-1updates and global-maximum queries as anx-window of widthWslides left to right). WhenW + H <= P // 2letsWvary andP // 2is modest (e.g.,<= 50), running oneO(N log N)sweep per integer widthW in 0..(P // 2)achievesO(P * N log N)time; if bothNandPare huge, no sub-quadratic exact worst-case algorithm is known, so clarifying parameter regimes with the interviewer is essential.
Follow-up questions
- Does the maximum point count change if the rectangle's perimeter must equal P exactly rather than at most P?
- How would you modify the solution if boundary points were excluded and only strictly interior points counted?
- If the input contained up to 100,000 points instead of 200, what algorithmic tools could avoid an O(N^3) scan?
Similar questions
- Equalizing Nine Stones Across a 3x3 Grid
- Fix and Extend a Nested Price Tracker
- Internal Corporate Knowledge Retrieval and Agent Platform
- Object-Oriented Pizza Order Pricing Pipeline
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger