BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges9 of 14 in topic

880. Fast k-means assignment step

MediumOptimization challenges Pro

Why it matters k-means is still used for vector quantization, IVF indexes in vector databases and data dedup. The assignment step is where the time goes.

assign_clusters(X, C) returns, for every point, the index of the nearest centroid by squared Euclidean distance. Ties go to the lower centroid index (np.argmin behaviour).

Inputs: X is a list or ndarray of shape (n, d), C of shape (k, d).

Return an ndarray of ints with shape (n,).

The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 90 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.

Functiondef assign_clusters(X, C)

Example 1

Input: assign_clusters([[0.0, 0.0], [9.0, 9.0], [4.0, 5.0]], [[0.0, 1.0], [10.0, 10.0]])

Output: [0, 1, 0]

Example 2

Input: X = [[1.0]], C = [[0.0], [2.0]]

Output: [0]

Constraints

  • C has shape (k, d)
  • Python 3 with NumPy. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Loop over centroids, not points, if you loop at all.

Hint 2

Stack the k distance columns into an (n, k) array.

Hint 3

argmin along axis 1.

Common mistakes
  • argmin along axis 0.
  • Using the expansion ||x||^2 - 2 x.c + ||c||^2, which can break exact ties because of rounding.
  • Taking sqrt (not needed for argmin).
Understand the idea

The loop costs one NumPy call per point. Looping over the k centroids instead (k is small) and computing all n distances in each pass gives an (n, k) distance matrix with only k NumPy calls. Full broadcasting X[:, None] - C[None] also works but builds an (n, k, d) array.

Shapes and data flow
X: (n, d). C: (k, d). distances: (n, k). Output: (n,).
Topics
Optimization challenges
Similar questions
  • Vectorise pairwise Euclidean distancesMedium
  • Group-by mean without a Python loopMedium
  • Fast 2D valid convolutionMedium
  • Top-k indices for every rowMedium
All Optimization challenges problems
Report
880 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
import numpy as np
​
def assign_clusters(X, C):
X = np.asarray(X, dtype=float)
C = np.asarray(C, dtype=float)
out = np.zeros(X.shape[0], dtype=int)
for i in range(X.shape[0]):
out[i] = int(np.argmin(((C - X[i]) ** 2).sum(axis=1)))
return out
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS