Skip to content

Resource · Guide or article

k-Nearest Neighbors Algorithm

Explains k-nearest neighbors classification by majority vote of the closest points, a common ML-basics interview topic.

Reviewed

Open the original: k-Nearest Neighbors Algorithm (opens the original site in a new tab)

Add to a roadmap

Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.

Source content: English

The k-nearest neighbors algorithm (k-NN) is a supervised Machine Learning algorithm. It's a classification algorithm, determining the class of a sample vector using a sample data. In k-NN classification, the output is a class membership. An object is classified by a plurality vote of its neighbors, with the object being assigned to the class most common among its k nearest neighbors (k is a positive integer, typically small). If k = 1, then the object is simply assigned to the class of that single nearest neighbor. The idea is to calculate the similarity between two data points on the basis of a distance metric. Euclidean distance is used mostly for this task.

PrepKit overview

PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.

Suited to
The source does not state a level
Format
Reference

What it covers

  • Five-step procedure: compute distances, sort, take the first K labels, report the mode.
  • Worked figure where k = 3 and k = 5 give different classes for the same point.
  • Advice to prefer odd K, usually 3 or 5, to avoid ties.

How to use it

PrepKit study advice, not a claim made by the source.

Classify a few points on a hand-drawn 2D grid with k = 1, 3, and 5, then code it and explain why the answers change.

Scope and limitations

Brief, image-based examples from Wikipedia and GeeksForGeeks; no complexity, feature scaling, or exercises. A Portuguese translation is linked.

Access and format

English README on GitHub, free, from the MIT-licensed trekhleb/javascript-algorithms repository.

Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88

Evidence behind this overview
  • src/algorithms/ml/knn/README.md

Pages that include this

Get the PrepKit newsletter

Optional. You don't need it to use PrepKit.

How we handle your email