How do you find the top K elements in streaming data, optimizing for time complexity better than a heap-based approach?
Asked in the Phone Screen stage. The interviewer was dissatisfied with the standard heap solution, prompting the candidate to suggest a bucket-based method for O(1) time complexity.
Implement top_k_stream(stream, k, max_value). The stream contains integers from 0 through max_value. Return the largest k values in descending order, preserving duplicates. Use a bucket or direct-address counting strategy. The input guarantees 1 <= k <= len(stream).
def top_k_stream(stream, k, max_value):