K Most Frequent Elements

Medium Problems DSA practice problem on Onlearn.

Difficulty: medium.

Topics: How can we find the K most frequent elements in an array?, Hashing, Frequency Counting, Sorting, Heap, Bucket Sort, frequency counting, complexity analysis, sorting algorithms, heap, Hashing & Hash Maps, Heap (Priority Queue), Top K Frequent Elements (Bucket Sort).

Problem Statement Given an integer array nums and an integer k, return the k most frequent elements within the array. Note: The answer is guaranteed to be unique (i.e., the frequency of the kth most frequent element is strictly greater than the (k+1)th most frequent element). You may return the output in any order. Input Specification The first line contains a sequence of space separated integers representing the array nums. The second line contains a single integer k. Output Specification Print k space separated integers representing the most frequent elements. Constraints 1 ≤ nums.length ≤ 10^5 10^9 ≤ nums[i] ≤ 10^9 1 ≤ k ≤ number of unique elements in the array Sample Test Cases Sample Input 1 Sample Output 1 Explanation: Element 1 appears 3 times, element 2 appears 2 times, and element 3 appears 1 time. The 2 most frequent elements are 1 and 2. Sample Input 2 Sample Output 2 Explanation: There is only 1 element, so it is the most frequent. Sample Input 3 Sample Output 3 Explanation: Element 4 appears 3 times and element 1 appears 2 times. Difficulty Level Medium