Implement K-Means and Detect Divisible Subarrays
MicrosoftMachine Learning Engineer · OnsiteLast updated
This question evaluates a candidate's ability to implement an iterative clustering algorithm (K-means) and to reason about subarray sums modulo k, testing competencies in numerical computation, centroid management, edge-case handling, and efficient algorithm design.
Solve both coding tasks.
Part A: Implement K-Means Clustering
Implement K-means clustering for a set of points.
Given:
points: a list ofnpoints, where each point is a list ofdnumeric coordinates.k: the number of clusters.max_iterations: the maximum number of Lloyd iterations to run.tolerance: stop early if every centroid moves by at most this Euclidean distance.
Use the first k points as the initial centroids. In each iteration:
- Assign every point to the nearest centroid using squared Euclidean distance. Break ties by choosing the smallest centroid index.
- Recompute each centroid as the coordinate-wise mean of the points assigned to it.
- If a cluster becomes empty, keep its centroid unchanged for that iteration.
Return the final centroid coordinates and the cluster assignment for each input point.
Discuss edge cases such as invalid k, duplicate points, empty clusters, and convergence.
Part B: Detect a Divisible-Sum Subarray
Given an integer array nums and a positive integer k, return true if there exists a contiguous subarray of length at least 2 whose sum is divisible by k. Otherwise return false.
A sum is divisible by k if sum % k == 0.
Example:
- Input:
nums = [23, 2, 4, 6, 7],k = 6 - Output:
true - Explanation: The subarray
[2, 4]has sum6, which is divisible by6.
Constraints:
1 <= nums.length <= 1000000 <= nums[i] <= 10000000001 <= k <= 1000000000
Aim for an O(n) solution.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.