Skip to content
DeepForgeby svx
All problems
MediumML Fundamentalsml-197

Nearest Neighbor Matching

Problem

For each treated unit, match the control unit with the smallest distance. distances is a matrix with one row per treated unit.

Return the matched control index per row (ties keep the smallest index); rows with no controls yield -1. Empty input returns [].

Hint

Greedy nearest-neighbor matching picks the closest control for each treated unit.

Test cases

case 1
in: [[[0.5,0.2,0.9],[0.7,0.6,0.1]]]
expected: [1,2]
case 2
in: [[[0.3,0.3]]]
expected: [0]
case 3
in: [[[0.1],[],[0.2]]]
expected: [0,-1,0]
case 4
in: [[]]
expected: []
Starter codePython
def nearest_neighbor_matching(distances):
    # Your code here
    pass

4 test cases · run your code against them in the editor