Hierarchical Clustering — ML Technical Interview Questions & Answers

Building a tree of nested clusters.

Hierarchical Clustering

  • Simple meaning: Hierarchical clustering builds a tree of groups. Bottom-up: every student starts alone, closest pair merges, repeat until one family. The dendrogram is that family tree.
  • Picture: Cut the tree at a height to get 3 groups. You don’t have to pick k at the start — you pick a cut later. Slow on huge sheets.
  • Linkage (single / complete / average) changes who merges. sklearn: AgglomerativeClustering.
  • Trap: reading the dendrogram as a proven taxonomy. Trap: single linkage chaining into one long snake.

Technical Interview Tip: Merge closest groups. Draw the dendrogram. Cut to get k.

Code Examples for Hierarchical Clustering

Hierarchical 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))

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

How to Explain Hierarchical Clustering to an Interviewer

What is a dendrogram?

Tree of merges Cut it to pick groups

Agglomerative means?

Bottom-up merging