KatInterview

Rank Point Pairs by Bounding Hyperrectangle Volume

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingpair-enumerationgeometry

Last updated

Enumerate point pairs in d dimensions, compute the volume of the box they span, drop flat boxes, and return the rest in a strict multi-key order.

You are given a list of n points in d-dimensional space. Point i (0-based) has the integer coordinates points[i].

Any two distinct indices i < j define an axis-aligned box whose opposite corners are points[i] and points[j]. On each axis, the side length of this box is the absolute difference between the two points' coordinates on that axis. The box's volume is the product of its d side lengths. When d = 2, the box is a rectangle and the volume is its area. Your solution must work for every d in the allowed range.

Find every pair whose box has a volume greater than zero, and report each one together with its volume.

Function

def rank_box_pairs(points: List[List[int]]) -> List[List[int]]:

Output format and rules

  • Every reported entry is a list [i, j, volume] with i < j, where i and j are indices into points.
  • A pair with volume 0 is not reported. This happens when the two points have the same coordinate on at least one axis, and it includes pairs of identical points.
  • Sort the result by volume from largest to smallest. If volumes are equal, put the smaller i first. If i is also equal, put the smaller j first.
  • If no pair qualifies, return an empty list.

Constraints

  • 1 <= n <= 300
  • 2 <= d <= 6, and every point has exactly d coordinates
  • -100 <= points[i][k] <= 100
  • Every volume is at most 200^6 = 6.4 * 10^13

Examples

Example 1

Input: rank_box_pairs([[1, 1], [4, 3], [1, 5], [3, 0]])

Output: [[2, 3, 10], [0, 1, 6], [1, 2, 6], [1, 3, 3], [0, 3, 2]]

Example 2

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

Output: [[0, 2, 8], [0, 1, 6]]

Example 3

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

Output: []

Hints

Hint 1

The output can contain every pair of points, so you need to look at all i < j pairs. With n at most 300 that is fine.

Hint 2

Do not hard-code x and y. Walk over the coordinates of both points together and multiply the absolute differences, stopping early if one difference is zero.

Hint 3

For the ordering, negate only the volume in the sort key, for example (-volume, i, j). Using reverse=True on the whole key would also flip the tie-breakers.