KatInterview

Smallest Axis-Aligned Box Around Scattered Points

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingarraysgeometrymin-max

Last updated

Scan a list of integer 2D points once to find the extreme x and y values, then report the enclosing axis-aligned box as a corner plus width and height.

Enclosing Box for a Set of Points

You are given a non-empty list of points on a 2D plane. Each point is a pair (x, y) of integers.

Find the smallest rectangle whose sides are parallel to the coordinate axes and which contains every point (points lying on the boundary count as contained).

Describe that rectangle with three values:

  1. its lower-left corner, as the pair (smallest x, smallest y) over all points,
  2. its width, the largest x minus the smallest x,
  3. its height, the largest y minus the smallest y.

Return these as (corner, width, height), where corner is a pair of two integers and width and height are integers.

Width and height are plain differences of coordinates, so do not add 1 to either. A rectangle may be degenerate: if all points share the same x, the width is 0; if they share the same y, the height is 0. A single point yields a corner equal to that point with width 0 and height 0.

Constraints

  • The list contains between 1 and 10^6 points.
  • Every coordinate is an integer in the range from -10^9 to 10^9.
  • Duplicate points may appear.

Examples

Example 1

Input: bounding_box([[1, 1], [3, 4], [0, 2]])

Output: [[0, 1], 3, 3]

Example 2

Input: bounding_box([[5, 5]])

Output: [[5, 5], 0, 0]

Hints

Hint 1

Which points actually determine the rectangle? Only the ones holding the smallest and largest x, and the smallest and largest y.

Hint 2

Initialize all four extremes from the first point, then walk through the rest and widen each bound whenever a point falls outside it.

Hint 3

Check x and y updates independently for every point (separate `if` statements), since one point may improve both an x bound and a y bound. Width is max_x - min_x with no +1.