BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges8 of 14 in topic

879. IoU matrix for two sets of boxes

MediumOptimization challenges Pro

Why it matters IoU matrices drive non-max suppression, anchor matching and detection metrics like mAP. Production detectors compute millions of them per batch.

iou_matrix(a, b) returns the intersection over union between every box in a and every box in b. Boxes are [x1, y1, x2, y2] with x1 <= x2 and y1 <= y2. Intersection width and height are clipped at 0. If the union area is 0, the IoU is 0.0.

Inputs: a is a list or ndarray of shape (n, 4), b of shape (m, 4).

Return an ndarray of floats with shape (n, m). No rounding.

The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 50 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.

Functiondef iou_matrix(a, b)

Example 1

Input: iou_matrix([[0.0, 0.0, 2.0, 2.0]], [[1.0, 1.0, 3.0, 3.0], [0.0, 0.0, 2.0, 2.0], [5.0, 5.0, 6.0, 6.0]])

Output: [[0.1429, 1.0, 0.0]]

Example 2

Input: a = [[0.0, 0.0, 0.0, 0.0]], b = [[0.0, 0.0, 0.0, 0.0]]

Output: [[0.0]]

Constraints

  • b has shape (m, 4)
  • Python 3 with NumPy. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Index columns with a[:, None, 0] and b[None, :, 0].

Hint 2

Clip intersection width and height at 0.

Hint 3

Use np.where to avoid dividing by zero.

Common mistakes
  • Forgetting the clip, so far apart boxes get positive intersection.
  • Subtracting the intersection twice in the union.
  • Letting 0 / 0 produce nan.
Understand the idea

Broadcast a as (n, 1) and b as (1, m) for each coordinate. The intersection corners are the max of the top-left corners and the min of the bottom-right corners; clip widths and heights at 0 for boxes that do not overlap. Guard the division so zero-area unions give 0.0 instead of nan.

Shapes and data flow
a: (n, 4), b: (m, 4). Every intermediate: (n, m).
Topics
Optimization challenges
Similar questions
  • Vectorise pairwise Euclidean distancesMedium
  • Group-by mean without a Python loopMedium
  • Fast 2D valid convolutionMedium
  • Top-k indices for every rowMedium
All Optimization challenges problems
Report
879 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np
​
def iou_matrix(a, b):
a = np.asarray(a, dtype=float).tolist()
b = np.asarray(b, dtype=float).tolist()
out = np.zeros((len(a), len(b)))
for i, (ax1, ay1, ax2, ay2) in enumerate(a):
for j, (bx1, by1, bx2, by2) in enumerate(b):
iw = max(0.0, min(ax2, bx2) - max(ax1, bx1))
ih = max(0.0, min(ay2, by2) - max(ay1, by1))
inter = iw * ih
union = (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - inter
out[i, j] = inter / union if union > 0 else 0.0
return out
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS