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 x values [-2, 4, 1], the extremes are -2 and 4, giving width = 4 - (-2) = 6. Across y values [5, 1, 6], the extremes are 1 and 6, giving height = 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, where x and y are integers.

Step-by-step walkthrough

  1. 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) = 6
    

    Notice two crucial details in this picture:

    • The lower-left corner (-2, 1) is not one of the input points: min_x = -2 came from (-2, 5) while min_y = 1 came from (4, 1).
    • Width and height are geometric spans (max_x - min_x and max_y - min_y), so a single point like [(7, -3)] in Example 2 has width 0 and height 0.
  2. 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 have left <= x <= right and bottom <= y <= top for all points.
    • That forces left <= min_x, right >= max_x, bottom <= min_y, and top >= max_y.
    • Setting the walls right on min_x, max_x, min_y, and max_y encloses 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 x values and sort all y values to read the first and last entries in O(n log n) time. Because we only care about the extremes — not the relative order of interior points — a single O(n) scan is enough.

  3. 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_x would stay stuck at 0 even though no point has x = 0. Likewise, if all coordinates are negative, max_x and max_y would stay stuck at 0.
    • Why not float('inf') and float('-inf')? Those sentinel values (dummy placeholder numbers chosen outside the valid range so the first real element overwrites them) would mix float types with int types until overwritten. Starting from points[0] keeps every variable an int from line 1 and is already exact when len(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
    
  4. Expand the boundaries in a single pass

    Next, visit every (x, y) in points and widen any wall that the point crosses. Two implementation details matter here:

    • Iterate over points, not points[1:]: In Python, slicing points[1:] allocates a brand-new list copying up to 10^6 - 1 references (O(n) extra memory). Re-checking points[0] once costs two comparisons and keeps extra space strictly O(1).
    • Keep the x test separate from the y test: Within x, a coordinate smaller than min_x cannot also exceed max_x (so elif x > max_x: is safe), and the same holds within y. Never chain y onto x with elif, because a single point like (-5, 10) can set a new min_x and a new max_y at 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
    
  5. Compute bottom-left corner, width, and height

    Once the loop finishes, assemble bottom_left = (min_x, min_y), width = max_x - min_x, and height = max_y - min_y. With coordinates in [-10^9, 10^9], width and height can reach 2 * 10^9; Python arbitrary-precision integers handle this effortlessly (whereas in C++ or Java you would use a 64-bit long to 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)
    
  6. 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_y
    

    Finally: - bottom_left = (-2, 1) - width = 4 - (-2) = 6 - height = 6 - 1 = 5

    Returning ((-2, 1), 6, 5) matches Example 1.

  7. 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)]:

  1. Start at (-2, 5): Seed min_x = -2, max_x = -2, min_y = 5, max_y = 5.
  2. Visit (4, 1): 4 > -2 updates max_x = 4, and 1 < 5 updates min_y = 1.
  3. Visit (1, 6): x = 1 already lies inside [-2, 4], while 6 > 5 updates max_y = 6.
  4. Result: Lower-left vertex (-2, 1) (notice (-2, 1) wasn't even one of the input points!), width 4 - (-2) = 6, height 6 - 1 = 5, returning ((-2, 1), 6, 5).

Complexity

  • Time: O(n) — We visit each of the n coordinates in points once and perform at most four integer comparisons per point, followed by two subtractions at the end.
  • Space: O(1) extra space — Regardless of whether points holds 1 point or 10^6 points, 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 x produce width = 0 with positive height, and points sharing the same y produce height = 0 with positive width.
  • All-negative or all-positive coordinates: Seeding from points[0] instead of 0 prevents 0 from acting as a phantom point at the origin.
  • Lower-left corner not in points: For [(-2, 5), (4, 1)], min_x = -2 and min_y = 1 come from different points, producing corner (-2, 1).
  • Large coordinate spans (-10^9 to 10^9): max_x - min_x can reach 2 * 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 approach 2^31.

Common mistakes

  • Initializing min_x, max_x, min_y, max_y to 0: Fails whenever every coordinate on an axis has the same sign (for example, [(3, 4), (5, 6)] would falsely get min_x = 0, min_y = 0).
  • Chaining x and y updates into one if / elif / elif / elif chain: If x > max_x triggers first, Python skips the y branches, missing a point like (4, 1) in Example 1 that sets both a new max_x and a new min_y.
  • Slicing points[1:] in the for loop: In Python, points[1:] allocates a shallow copy of almost the entire 10^6-element list, turning O(1) extra memory into O(n).
  • Adding 1 to width or height (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 / max generator passes: Calling min(p[0] for p in points), max(p[0] for p in points), min(p[1] for p in points), and max(p[1] for p in points) is still O(n) time and O(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 2D NumPy array of shape (n, 2), arr.min(axis=0) and arr.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, and max_y, all four vertices follow immediately without rescanning points. 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). If width == 0 or height == 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 from 2n down to 1.5n via pairwise tournament comparison (grouping points two at a time, comparing their x coordinates against each other first, and then comparing only the smaller to min_x and the larger to max_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, and max_y inside a small tracker object initialized to None, set all four bounds on the first arriving point, and update them in O(1) time and O(1) space per point. Two workers ingesting separate partitions of a high-volume stream can also combine their partial boxes in O(1) time by taking min of the minima and max of the maxima.

Follow-up questions

Similar questions

More Upstart interview questions

All 51 Upstart questions →