Skip to content

Latest commit

 

History

History
71 lines (42 loc) · 1.26 KB

File metadata and controls

71 lines (42 loc) · 1.26 KB

LeetCode – 347. Top K Frequent Elements

Problem Statement

You are given an integer array nums and an integer k.
Your task is to return the k most frequent elements in the array.

Description

  • Count how many times each number appears.

  • Return the elements with the highest frequencies.

  • Order does not matter.

This is a classic frequency + heap/hashmap problem.

Input

An array nums
An integer k

Output

An array of k elements that appear most frequently.

Examples

Example 1
Input:
nums = [1,1,1,2,2,3]
k = 2

Output:
[1,2]

Explanation:
1 appears 3 times, 2 appears 2 times → they are top 2.

Example 2
Input:
nums = [1]
k = 1

Output:
[1]

Constraints

  • 1 ≤ nums.length ≤ 10⁵

  • k ≥ 1

  • Answer must be among the unique elements

Hints

  • Use a frequency map to count occurrences

  • Use a heap OR bucket sort to pick top k

  • Python’s heapq supports min-heaps; push (-frequency, value) OR use a size-k heap

Explanation

Step 1: Count frequencies using a dictionary
Step 2: Use a heap (or buckets) to extract k elements with the highest frequency
Step 3: Return those elements

This problem tests knowledge of hashmaps and priority queues.