Loading…
Loading…
Given an array and an integer k, return the k most frequent elements.
Input: 1 1 1 2 2 3, k = 2
Output: 1 2
Count each value's frequency with a hash map, then find the k keys with the highest counts — a heap keyed on frequency does this in O(n log k) without a full sort of every distinct value.
Line 1: the array, space-separated
Line 2: k
Print the k most frequent values, space-separated, sorted ascending for a deterministic check.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.