Smallest Axis-Aligned Enclosing Box
Easy · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
You receive a non-empty collection points of integer planar coordinates (x, y). Determine the tightest rectangle with horizontal and vertical sides that covers every coordinate in points (points lying directly on an edge or corner count as covered).
Report that enclosing box as a 3-tuple ((left_x, bottom_y), width, height) where:
- (left_x, bottom_y) is the lower-left vertex of the box,
- width is the horizontal span between the leftmost and rightmost coordinates, and
- height is the vertical span between the lowest and highest coordinates.
Note that (left_x, bottom_y) does not need to belong to points, and degenerate boxes (where every point shares the same x value, the same y value, or both) have 0 for the corresponding dimension.
def get_bounding_rectangle(points: List[Tuple[int, int]]) -> Tuple[Tuple[int, int], int, int]:
Examples
Example 1
- Input:
points = [(-2, 5), (4, 1), (1, 6)] - Output:
((-2, 1), 6, 5) - Explanation: Across
xvalues[-2, 4, 1], the extremes are-2and4, givingwidth = 4 - (-2) = 6. Acrossyvalues[5, 1, 6], the extremes are1and6, givingheight = 6 - 1 = 5. Combining the two minima places the lower-left vertex at(-2, 1).
Example 2
- Input:
points = [(7, -3)] - Output:
((7, -3), 0, 0) - Explanation: With only one location present, both horizontal and vertical extremes coincide at
(7, -3), yielding zero span along both axes.
Constraints
1 <= len(points) <= 10^6- Each element
(x, y)satisfies-10^9 <= x, y <= 10^9, wherexandyare integers.
Step-by-step walkthrough
Understand the problem and output shape
We are given a non-empty list of 2D integer coordinates
(x, y)and asked for the tightest axis-aligned enclosing box — a rectangle whose edges run strictly horizontal and vertical (parallel to the x-axis and y-axis, never tilted) — that covers every coordinate.We must return
((min_x, min_y), width, height). Plotting Example 1 (points = [(-2, 5), (4, 1), (1, 6)]) makes the geometry clear immediately:y 6 | . . . . *(1,6) . . top = max_y = 6 5 | *(-2,5) : 4 | : : height = 6 - 1 = 5 3 | : : 2 | : : 1 | +--------------*(4,1) bottom = min_y = 1 | (-2,1) 0 +----------------------- x -2 -1 0 1 .. 4 |<--- width = 6 -->| left = -2, right = 4, width = 4 - (-2) = 6Notice two crucial details in this picture:
- The lower-left corner
(-2, 1)is not one of the input points:min_x = -2came from(-2, 5)whilemin_y = 1came from(4, 1). - Width and height are geometric spans (
max_x - min_xandmax_y - min_y), so a single point like[(7, -3)]in Example 2 has width0and height0.
- The lower-left corner
Why the four coordinate extremes determine the box
Any axis-aligned rectangle is completely fixed by four straight walls: its left (
x = left), right (x = right), bottom (y = bottom), and top (y = top) edges.- To enclose every point
(x, y), we must haveleft <= x <= rightandbottom <= y <= topfor all points. - That forces
left <= min_x,right >= max_x,bottom <= min_y, andtop >= max_y. - Setting the walls right on
min_x,max_x,min_y, andmax_yencloses every point while making the box as tight as possible: moving any wall inward would leave out the point that set that extreme.
A naive solution might sort all
xvalues and sort allyvalues to read the first and last entries inO(n log n)time. Because we only care about the extremes — not the relative order of interior points — a singleO(n)scan is enough.- To enclose every point
Initialize from the first point
Before scanning, our four running boundaries need starting values. Unpacking
points[0]is the cleanest and safest choice:- Why not start at
0? If all input points are positive (say[(3, 4), (5, 6)]),min_xwould stay stuck at0even though no point hasx = 0. Likewise, if all coordinates are negative,max_xandmax_ywould stay stuck at0. - Why not
float('inf')andfloat('-inf')? Those sentinel values (dummy placeholder numbers chosen outside the valid range so the first real element overwrites them) would mixfloattypes withinttypes until overwritten. Starting frompoints[0]keeps every variable anintfrom line 1 and is already exact whenlen(points) == 1.
Unpacking with
first_x, first_y = points[0]also works seamlessly whether the test runner passes tuples(x, y)or two-element lists[x, y].# Phase 1: Seed all four outer boundaries from the first real point. # Starting at 0 would fail when all coordinates are positive or all negative. first_x, first_y = points[0] min_x = first_x max_x = first_x min_y = first_y max_y = first_y- Why not start at
Expand the boundaries in a single pass
Next, visit every
(x, y)inpointsand widen any wall that the point crosses. Two implementation details matter here:- Iterate over
points, notpoints[1:]: In Python, slicingpoints[1:]allocates a brand-new list copying up to10^6 - 1references (O(n)extra memory). Re-checkingpoints[0]once costs two comparisons and keeps extra space strictlyO(1). - Keep the
xtest separate from theytest: Withinx, a coordinate smaller thanmin_xcannot also exceedmax_x(soelif x > max_x:is safe), and the same holds withiny. Never chainyontoxwithelif, because a single point like(-5, 10)can set a newmin_xand a newmax_yat the exact same time!
# Phase 2: Sweep every point once and push the four walls outward when needed. for x, y in points: if x < min_x: min_x = x elif x > max_x: max_x = x if y < min_y: min_y = y elif y > max_y: max_y = y- Iterate over
Compute bottom-left corner, width, and height
Once the loop finishes, assemble
bottom_left = (min_x, min_y),width = max_x - min_x, andheight = max_y - min_y. With coordinates in[-10^9, 10^9],widthandheightcan reach2 * 10^9; Python arbitrary-precision integers handle this effortlessly (whereas in C++ or Java you would use a 64-bitlongto avoid signed 32-bit overflow if coordinates went slightly wider).# Phase 3: Compute geometric span (no +1: a single point has width 0 and height 0). bottom_left = (min_x, min_y) width = max_x - min_x height = max_y - min_y return (bottom_left, width, height)Trace Example 1 step by step
Let's trace
points = [(-2, 5), (4, 1), (1, 6)]:Step min_x max_x min_y max_y What changed? --------------- ----- ----- ----- ----- ---------------------------------- Init points[0] -2 -2 5 5 Seeded from (-2, 5) Point (-2, 5) -2 -2 5 5 Already inside bounds Point (4, 1) -2 4 1 5 4 > max_x and 1 < min_y (both!) Point (1, 6) -2 4 1 6 x=1 is inside [-2, 4]; 6 > max_yFinally: -
bottom_left = (-2, 1)-width = 4 - (-2) = 6-height = 6 - 1 = 5Returning
((-2, 1), 6, 5)matches Example 1.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def get_bounding_rectangle(points: List[Tuple[int, int]]) -> Tuple[Tuple[int, int], int, int]: # Phase 1: Seed all four outer boundaries from the first real point. # Starting at 0 would fail when all coordinates are positive or all negative. first_x, first_y = points[0] min_x = first_x max_x = first_x min_y = first_y max_y = first_y # Phase 2: Sweep every point once and push the four walls outward when needed. # Loop over 'points' directly instead of slicing 'points[1:]', which would copy # up to 10^6 points and cost O(n) extra memory. for x, y in points: # Check x and y independently: a single point like (-5, 10) can set both # a new min_x and a new max_y on the same iteration. if x < min_x: min_x = x elif x > max_x: max_x = x if y < min_y: min_y = y elif y > max_y: max_y = y # Phase 3: Compute geometric span (no +1: a single point has width 0 and height 0). # Note that bottom_left (min_x, min_y) need not be one of the input points. bottom_left = (min_x, min_y) width = max_x - min_x height = max_y - min_y return (bottom_left, width, height)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine hammering pushpins into a coordinate wall and placing a rectangular picture frame with strictly horizontal and vertical edges around all of them — an axis-aligned enclosing box (a rectangle whose sides run parallel to the x-axis and y-axis rather than tilted at an angle). If you slide the left, right, bottom, and top edges of the frame inward until each edge hits its outermost pushpin, the four walls stop at min_x, max_x, min_y, and max_y. The lower-left vertex is simply (min_x, min_y), the horizontal span is max_x - min_x, and the vertical span is max_y - min_y.
A naive attempt might sort all x coordinates and sort all y coordinates to read off the smallest and largest values, or compare every pair of points to find the widest span. Sorting takes O(n log n) time and pair comparisons take O(n^2) time, both doing unnecessary work on interior points that never touch the outer frame. Because the x boundaries and y boundaries are completely independent, a single linear scan tracking four running integers (min_x, max_x, min_y, max_y) finds the exact frame in one pass.
Let's walk through Example 1 with points = [(-2, 5), (4, 1), (1, 6)]:
- Start at
(-2, 5): Seedmin_x = -2, max_x = -2, min_y = 5, max_y = 5. - Visit
(4, 1):4 > -2updatesmax_x = 4, and1 < 5updatesmin_y = 1. - Visit
(1, 6):x = 1already lies inside[-2, 4], while6 > 5updatesmax_y = 6. - Result: Lower-left vertex
(-2, 1)(notice(-2, 1)wasn't even one of the input points!), width4 - (-2) = 6, height6 - 1 = 5, returning((-2, 1), 6, 5).
Complexity
- Time:
O(n)— We visit each of thencoordinates inpointsonce and perform at most four integer comparisons per point, followed by two subtractions at the end. - Space:
O(1)extra space — Regardless of whetherpointsholds1point or10^6points, we only store four running integer boundaries (min_x,max_x,min_y,max_y) and never copy or slice the input list.
Edge cases
- Single point
[(7, -3)]: All four boundaries equal that point's coordinates, cleanly returning((7, -3), 0, 0)with zero width and zero height. - Collinear points (vertical or horizontal line): Points sharing the same
xproducewidth = 0with positiveheight, and points sharing the sameyproduceheight = 0with positivewidth. - All-negative or all-positive coordinates: Seeding from
points[0]instead of0prevents0from acting as a phantom point at the origin. - Lower-left corner not in
points: For[(-2, 5), (4, 1)],min_x = -2andmin_y = 1come from different points, producing corner(-2, 1). - Large coordinate spans (
-10^9to10^9):max_x - min_xcan reach2 * 10^9; Python ints never overflow, though in Java or C++ you should compute differences in a 64-bit integer to avoid signed 32-bit overflow when coordinates approach2^31.
Common mistakes
- Initializing
min_x,max_x,min_y,max_yto0: Fails whenever every coordinate on an axis has the same sign (for example,[(3, 4), (5, 6)]would falsely getmin_x = 0, min_y = 0). - Chaining
xandyupdates into oneif / elif / elif / elifchain: Ifx > max_xtriggers first, Python skips theybranches, missing a point like(4, 1)in Example 1 that sets both a newmax_xand a newmin_y. - Slicing
points[1:]in theforloop: In Python,points[1:]allocates a shallow copy of almost the entire10^6-element list, turningO(1)extra memory intoO(n). - Adding
1towidthorheight(max_x - min_x + 1): That counts discrete grid cells rather than geometric span and fails Example 2 (((7, -3), 0, 0)).
Alternative approaches
- Separate
min/maxgenerator passes: Callingmin(p[0] for p in points),max(p[0] for p in points),min(p[1] for p in points), andmax(p[1] for p in points)is stillO(n)time andO(1)space, but traverses the list four times instead of once (and fails if the input is a single-pass iterator). - Vectorized NumPy reduction: If coordinates already live in a
2DNumPy array of shape(n, 2),arr.min(axis=0)andarr.max(axis=0)compute the extremes inside compiled C loops.
Follow-up questions
- How would you adapt the function if the caller wanted all four vertices of the enclosing box instead of corner, width, and height? Once you have
min_x,max_x,min_y, andmax_y, all four vertices follow immediately without rescanningpoints. Listed counterclockwise starting at the lower-left, they are(min_x, min_y),(max_x, min_y),(max_x, max_y), and(min_x, max_y). Ifwidth == 0orheight == 0(a single point or a line segment), some of those four coordinate pairs coincide unless the specification asks for unique vertices. - Can any deterministic algorithm beat linear runtime or constant extra memory on this problem, or only reduce constant factors? Neither asymptotic bound can be improved:
O(1)auxiliary space is already minimal, and any deterministic algorithm that leaves even one point unread could miss an arbitrarily distant outlier. However, you can cut coordinate comparisons per axis from2ndown to1.5nvia pairwise tournament comparison (grouping points two at a time, comparing theirxcoordinates against each other first, and then comparing only the smaller tomin_xand the larger tomax_x). - How would your design change if coordinates arrived continuously over an unbounded feed and callers queried the current box on demand? Because our loop never revisits past elements, it already forms an online algorithm (an algorithm that updates its state incrementally per arriving item without storing the history). Wrap
min_x,max_x,min_y, andmax_yinside a small tracker object initialized toNone, set all four bounds on the first arriving point, and update them inO(1)time andO(1)space per point. Two workers ingesting separate partitions of a high-volume stream can also combine their partial boxes inO(1)time by takingminof the minima andmaxof the maxima.
Follow-up questions
- How would you adapt the function if the caller wanted all four vertices of the enclosing box instead of corner, width, and height?
- Can any deterministic algorithm beat linear runtime or constant extra memory on this problem, or only reduce constant factors?
- How would your design change if coordinates arrived continuously over an unbounded feed and callers queried the current box on demand?
Similar questions
- Dining Hall Revenue With FIFO Waitlist
- Alphabetical Word Frequency Counts
- Reconstruct Scrambled Sentences Using Endpoint and Anagram Rules
- Maximum Substring Length Within K Unique Characters
- Maximum First-to-Last Letter Distance in Text
- Longest Non-Southward Eastbound Itinerary from CSV
More Upstart interview questions
- Half-Life Survival, Bidirectional Regression, Door Switching, and Die Coverage Easy
- Observational Causal Lift and Multi-Arm Launch Forecasting Easy
- Multiply Recipe Ingredient Amounts Easy Pro
- Probability, Bayes, and Regression Metrics Medium Pro
- Optimal Sensor Fusion and 2D Random-Walk Coordinate Correlations Easy Pro
- Dining Hall Revenue With FIFO Waitlist Medium Pro
- Debiasing Household Size Probabilities From Child Surveys Easy Pro
- Alphabetical Word Frequency Counts Medium Pro
- Reconstruct Scrambled Sentences Using Endpoint and Anagram Rules Medium Pro
- Marketing Funnel Analysis and Incremental Spend Allocation Hard Pro