Skip to content

Resource · Guide or article

k-Means Algorithm

Introduction to k-Means clustering for candidates who may be asked to explain or code a simple unsupervised ML algorithm.

Reviewed

Open the original: k-Means 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-Means algorithm is an unsupervised Machine Learning algorithm. It's a clustering algorithm, which groups the sample data on the basis of similarity between dimensions of vectors. In k-Means classification, the output is a set of classes assigned to each vector. Each cluster location is continuously optimized in order to get the accurate locations of each cluster such that they represent each group clearly. The idea is to calculate the similarity between cluster location and data vectors, and reassign clusters based on it. 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

  • Six-step loop: initialize k centroids, assign points by distance, recompute centroids, repeat.
  • Euclidean distance as the usual similarity measure.
  • A convergence animation and the observation that centroid movement shrinks over iterations.
  • Code Examples links the folder's JavaScript implementation and its test file.

How to use it

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

Using only the six steps, code k-Means on a small 2D dataset, then compare with the folder's kMeans.js and its tests.

Scope and limitations

Brief: no guidance on choosing k, initialization pitfalls, or complexity. Code is JavaScript only. A Portuguese translation is linked.

Access and format

Free English README on GitHub in trekhleb/javascript-algorithms (MIT), next to the JavaScript source.

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

Evidence behind this overview
  • src/algorithms/ml/k-means/README.md

Pages that include this

Get the PrepKit newsletter

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

How we handle your email