Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

137. Non Max Suppression

medium
GeneralGeneral
staff

Non-Max Suppression (NMS) is a common post-processing step in object detection that removes duplicate bounding boxes for the same object. You’ll implement classic greedy NMS based on Intersection-over-Union (IoU), keeping only the most confident boxes.

The key overlap metric is:

IoU(A,B)=area(A∩B)area(A∪B)\text{IoU}(A, B) = \frac{\text{area}(A \cap B)}{\text{area}(A \cup B)}

Requirements

Implement the function

python

Rules:

  • Use greedy NMS: repeatedly pick the remaining box with the highest score, then suppress boxes that overlap it too much.
  • Compute IoU using the boxes’ intersection and union areas (treat intersection width/height as max(0, ...)).
  • Return the original indices of the kept boxes, ordered by decreasing scores.
  • Don’t use any prebuilt NMS/IoU utilities (e.g., from torchvision, cv2, or similar).
  • Use NumPy for vectorized IoU computation with the candidate box.

Example

python

Output:

python
Input Signature
ArgumentType
boxesnp.ndarray
scoresnp.ndarray
iou_thresholdfloat
Output Signature
Return NameType
valuelist

Constraints

  • Use only NumPy.

  • Return original indices sorted by score.

  • Suppress boxes if IoU > threshold.

Hint 1

Start by sorting the indices of the boxes by scores descending; you will iterate through this ordered list and build a keep list of original indices.

Hint 2

Implement an iou(box_a, boxes) calculation: compute intersection corners with max()/min(), then inter_w = max(0, xx2-xx1), inter_h = max(0, yy2-yy1), and iou = inter_area / union_area.

Hint 3

Greedy loop pattern: pop the highest-score index i, then filter remaining indices by keeping only those with IoU(i, others) <= iou_threshold. Use boolean masking to filter order array.

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
staff
senior
entry
Tags
non-max-suppression
intersection-over-union
greedy-algorithm
numpy
18 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit