Mid-level interview questionAsked at Lyft · interview write-up
Implement K-means from first principles without numerical libraries, with fixed initialisation, tie handling, convergence rules and a policy for empty clusters.
Model answer
def kmeans(points, init, max_iter=100, tol=1e-9):
cents = [list(c) for c in init]
for _ in range(max_iter):
groups = [[] for _ in cents]
for p in points:
d = [sum((a - b) ** 2 for a, b in zip(p, c))
for c in cents]
groups[d.index(min(d))].append(p)
new = []
for c, g in zip(cents, groups):
if not g:
new.append(c)
continue
n = len(g)
new.append([sum(x) / n for x in zip(*g)])
shift = max(sum((a - b) ** 2
for a, b in zip(c, m))
for c, m in zip(cents, new))
cents = new
if shift <= tol:
break
return cents, groups
State each rule before coding. Given initial centroids make runs deterministic. A tie goes to the lowest-index centroid, which taking the first minimum does. An empty cluster keeps its previous centroid; reseeding at the farthest point is the alternative. Stop when no centroid moves more than a tolerance, or at the iteration cap. Interviewers weigh these edge cases more than the loop.
Practise the rest
35 Training questions, 492 in all, each with a model answer. Free.
More from Lyft interview questions.
More Training interview questions
- Implement masked cross-entropy in NumPy that stays numerically stable, with label smoothing and a temperature.
- Build a pipeline that finds math documents in web crawls and scores their quality.
- Explain KL divergence for language models: which direction is which, what happens when supports don't match, and how it's used as a regulariser.
- When would you use mean squared error versus cross-entropy? And what is LoRA?
- Explain Adam and its bias correction, and why AdamW decouples weight decay.
- Explain policy types in RL and modern policy-gradient methods such as TRPO, PPO and GAE, then compare linear attention and grouped-query attention.