One-Nearest-Neighbor Classification
Problem statement
You are given a nonempty set of labeled training samples and a set of query samples. Each sample is an integer feature vector.
For every query, find the single training sample with the smallest squared Euclidean distance:
distance(a, b) = sum((a[i] - b[i])^2)
Examples
Example 1
trainingFeatures = [[0,0],[2,2],[5,5]]trainingLabels = [10,20,30]queries = [[1,1],[4,4]]return = [10,30]For [1,1], the first two training samples are tied at squared distance 2, so the earlier sample supplies label 10. For [4,4], the nearest sample is [5,5], which supplies label 30.
Unlock this recently reported problem
FastPrep Pro gives you full access to interview problems reported within the last week.
- Full problem statement and constraints
- 2 more worked examples, explained
- Guided hints and editorial
- Run your code on real test cases
Pro subscription, billed yearly — or $19 month-to-month. Cancel anytime.