Given an array and an integer k, return the k most frequent elements.
Example
Input: 1 1 1 2 2 3, k = 2
Output: 1 2
Approach
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.
Input format
Line 1: the array, space-separated
Line 2: k
Print the k most frequent values, space-separated, sorted ascending for a deterministic check.
Not solved yet
Ctrl+Enter
Editor
from collections import Counter
import heapq
nums = list(map(int, input().split()))
k = int(input())
counts = Counter(nums)
# TODO: the k keys with the highest counts.values() — heapq.nlargest is one option
Input (stdin)
Output
Run your code to see output here.
Isolated sandbox · not executed on your devicePowered by Judge0 CE (free, self-hosted). Runs in an isolated sandbox — not on your device.
Editor
from collections import Counter
import heapq
nums = list(map(int, input().split()))
k = int(input())
counts = Counter(nums)
# TODO: the k keys with the highest counts.values() — heapq.nlargest is one option
Input (stdin)
Output
Run your code to see output here.
Isolated sandbox · not executed on your devicePowered by Judge0 CE (free, self-hosted). Runs in an isolated sandbox — not on your device.