Top K Frequent Elements
Hard · Sorting
collections.Counter counts items for you. To pick the best few, you can sort by a key, or use heapq.nsmallest(k, items, key=...), which is faster when k is small.
A sort key can be a tuple: Python compares the first part, then the second on ties. So key=lambda item: (-count, value) means "highest count first, then smallest value".
Write top_k_frequent(nums, k) that returns the k most frequent numbers, ordered by count (highest first). When two numbers have the same count, the smaller number comes first. k is never larger than the number of distinct values.
Next: Sudoku Board Validator