Skip to content

Commit 38726ba

Browse files
authored
Create 05-00347-top-k-frequent-elements.py
1 parent cb92b1e commit 38726ba

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
2+
3+
# Example 1:
4+
# Input: nums = [1,1,1,2,2,3], k = 2
5+
# Output: [1,2]
6+
7+
# Example 2:
8+
# Input: nums = [1], k = 1
9+
# Output: [1]
10+
11+
# Constraints:
12+
# 1 <= nums.length <= 105
13+
# -104 <= nums[i] <= 104
14+
# k is in the range [1, the number of unique elements in the array].
15+
# It is guaranteed that the answer is unique.
16+
17+
# Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
18+
19+
# -------------------------------------------------------------------------------------------------------------------------------------------------
20+
21+
# HASHMAP
22+
23+
# create a hashmap where num is key and it's freq is the value
24+
# create a bucket list where index is freq and value at each index is a list of nums that has that freq
25+
# we are creating a bucket of frequencies because at max, all the elments in the nums list will be same, and will be in the last bucket
26+
# eg if there are nine 7's in the nums list and length of nums list = 9, so freq bucket list will from 0th index to 9th index = length 10
27+
# bucket list will be length of nums + 1, because there's a 0th index
28+
# create an o/p list res that is empty
29+
# iterate a loop on the bucket list in reverse order till 1st index(because 0th index will be empty)
30+
# because we want top frequent elements, so the later in list the higher the freq highest
31+
# iterate loop in the inner list(each bucket)
32+
# append in the res list
33+
# when length of res == k, return res
34+
35+
class Solution:
36+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
37+
38+
numToFreq = {}
39+
freqBuckets = [[] for i in range(len(nums) + 1)]
40+
41+
for n in nums:
42+
numToFreq[n] = 1 + numToFreq.get(n, 0)
43+
44+
for num, count in numToFreq.items():
45+
freqBuckets[count].append(num)
46+
47+
48+
res = []
49+
for i in range(len(freqBuckets) - 1, 0, -1):
50+
for j in freqBuckets[i]:
51+
res.append(j)
52+
if len(res) == k:
53+
return res
54+
55+
56+
Time complexity = O(n)
57+
Space complexity = O(n)

0 commit comments

Comments
 (0)