File tree Expand file tree Collapse file tree 1 file changed +13
-0
lines changed
hashmap/347_Top_K_Frequent_Elements Expand file tree Collapse file tree 1 file changed +13
-0
lines changed Original file line number Diff line number Diff line change @@ -45,3 +45,16 @@ def top_k_frequent(nums: list[int], k: int) -> list[int]:
45
45
46
46
* ** Time Complexity:** $O(n \cdot log(n))$
47
47
* ** 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.
You can’t perform that action at this time.
0 commit comments