A ThoughtWorks MLOps pipeline receives an array of integer feature IDs emitted by model-serving events. Implement a function that returns the k most frequently occurring feature IDs.
Rank IDs by descending frequency. If two IDs have the same frequency, rank the smaller ID first. Return exactly k IDs, or all distinct IDs if fewer than k exist.
Implement top_k_features(events, k):
events: a list of integers, where each integer is a feature ID.k: a positive integer.k distinct integers ordered by descending frequency and then ascending feature ID.The result must not contain duplicate IDs. The algorithm should avoid sorting every distinct ID when k is much smaller than the number of distinct IDs.
def top_k_features(events, k):