Skip to content

Commit 87bd67f

Browse files
committed
Add top k explanation
1 parent 4bf13b2 commit 87bd67f

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

hashmap/347_Top_K_Frequent_Elements/README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,16 @@ def top_k_frequent(nums: list[int], k: int) -> list[int]:
4545

4646
* **Time Complexity:** $O(n \cdot log(n))$
4747
* **Space Complexity:** $O(n)$
48+
49+
## Explanation of the Solution
50+
51+
1. Count Frequencies:
52+
* A dictionary `nums_hash` is used to store each number’s frequency in nums.
53+
* For each number in nums:
54+
* If the number exists in `nums_hash`, increment its count by 1.
55+
* If the number does not exist, add it to `nums_hash` with a count of 1.
56+
2. Sort by Frequency:
57+
* The dictionary keys (unique numbers) are sorted in descending order based on their frequency (`nums_hash[x]`).
58+
* `reverse=True` ensures higher frequencies appear first.
59+
3. Select Top k Elements:
60+
* The first `k` elements from the sorted list are returned.

0 commit comments

Comments
 (0)