K-Means Clustering — ML Technical Interview Questions & Answers

Partitioning data into k groups by similarity.

K-Means Clustering

  • Simple meaning: K-means puts every row in one of k groups. Pick k. Place k centres. Assign each student to the nearest centre. Move centres to the mean of their group. Repeat.
  • Picture: Three blobs of marks. k=3. Centres sit in the middle of each blob. k=2 will smash two blobs together. Elbow plot (inertia vs k) is a hint, not a law.
  • sklearn: KMeans(n_clusters=3). Scale first. Assumes round-ish similar-size blobs. Random start — n_init matters.
  • Trap: k-means on a banana-shaped group (use DBSCAN). Trap: not scaling. Trap: “the cluster is the true type”.

Technical Interview Tip: Nearest centre, then move the centre. Scale. Pick k with care.

Code Examples for K-Means Clustering

K-Means Clustering — working example

# Tiny 1D k-means-style update (k=2)
points = [1.0, 1.5, 2.0, 8.0, 8.5, 9.0]
c1, c2 = 1.0, 9.0
for _ in range(3):
    g1 = [p for p in points if abs(p - c1) <= abs(p - c2)]
    g2 = [p for p in points if abs(p - c1) > abs(p - c2)]
    c1 = sum(g1) / len(g1)
    c2 = sum(g2) / len(g2)
print(round(c1, 2), round(c2, 2), len(g1), len(g2))

K-Means Clustering — clustering groups unlabeled points; k-means alternates assignment and centroid updates.

How to Explain K-Means Clustering to an Interviewer

K-means steps?

Choose k Assign to nearest centre Update means Repeat

Why scale?

Distance to centres Big columns dominate