One-Nearest-Neighbor Classification with Manhattan Distance
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 Manhattan distance:
distance(a, b) = sum(abs(a[i] - b[i]))
Examples
Example 1
trainingFeatures = [[0,0],[3,0],[2,3]]trainingLabels = [10,20,30]queries = [[2,1],[2,3]]return = [20,30]The first query is two units from both the first and second rows, so the earlier of those tied nearest rows supplies label 20 only after checking all distances: its distances are 3, 2, and 2, making the second row the earliest minimum. The second query exactly matches the third row.
Unlock this recently reported problem
FastPrep Pro gives you full access to interview problems reported within the last week.
- Full problem statement and constraints
- 1 more worked example, explained
- Guided hints and editorial
- Run your code on real test cases
$99 billed yearly — or $19 month-to-month. Cancel anytime.