question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
find-longest-special-substring-that-occurs-thrice-i
Find Longest Special Sbustring that occurs thrice i
find-longest-special-sbustring-that-occu-xy3e
IntuitionApproachComplexity Time complexity: Space complexity: Code
Nityananadh
NORMAL
2025-03-25T08:19:13.201848+00:00
2025-03-25T08:19:13.201848+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maximumLength(String s) { int n = s.length(); int l = 1, r = n; if (!helper(s, n, l)) return -1; while (l + 1 < r) { int mid = (l + r) / 2; if (helper(s, n, mid)) l = mid; else r = mid; } return l; } private boolean helper(String s, int n, int x) { int [] cnt = new int [26]; int p = 0; for (int i = 0; i < n; i++) { while (s.charAt(p) != s.charAt(i)) p++; if (i - p + 1>= x) cnt[s.charAt(i) - 'a']++; if (cnt[s.charAt(i) - 'a'] > 2) return true; } return false; } } ```
0
0
['Java']
0
find-longest-special-substring-that-occurs-thrice-i
C++ Solution Beats 100%
c-solution-beats-100-by-dakshg-mh93
Code
dakshg
NORMAL
2025-03-07T03:18:21.854797+00:00
2025-03-07T03:18:21.854797+00:00
5
false
# Code ```cpp [] constexpr int maxlen = 301; class Solution { public: int maximumLength(string &s) { array<array<int, maxlen>, 26> cnt {}; int mx = -1, p = 0; s += '#'; for(int i = 1; i < s.size(); ++i) { if(s[i] == s[i - 1]) continue; int len = i - p, c = s[i - 1] - 'a'; if(len - 2 > 0) mx = max(mx, len - 2); ++cnt[c][len]; if(cnt[c][len] >= 3) mx = max(mx, len); if(len == 1) { p = i; continue; } cnt[c][len - 1] += 2; if(cnt[c][len - 1] >= 3) mx = max(mx, len - 1); p = i; } return mx; } }; ```
0
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Diff Array Approach Time Complexity O(n) Space Complexity O(n)
diff-array-approach-time-complexity-on-s-2j76
IntuitionThis is a more generic solution, that detects any subtring that occurs for k times. It is hard coded as three for this solution. The idea is that for e
stanlearningcoding
NORMAL
2025-03-06T06:23:07.693400+00:00
2025-03-06T06:23:07.693400+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> This is a more generic solution, that detects any subtring that occurs for k times. It is hard coded as three for this solution. The idea is that for each continuous character, if we want to count number of occurence of embedded substring, we can use the diff array. for example, we have continuous array length 3, then we can have array [1, 1, 1] the index is length -1. and we have 3 substrings of length 1, and 2 substrings of length 2, and 1 substring of length 3. And this information could be reconstructed if we do prefix sum from right to left. so each time when we see an element, we update the diff array based on the length of current continuous substring. see if we have length 2, we want to increment the diff array [1] by 1 # Approach <!-- Describe your approach to solving the problem. --> code explains itself hopefully # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) the string is iterated once, and the record 2d array is iterated once - Space complexity: O(1) bounded by 50 * 26 # Code ```python3 [] class Solution: def maximumLength(self, s: str) -> int: records = [[] for _ in range(26)] max_count = [0 for _ in range(26)] prev = -1 count = 0 for c in s: cur_record = records[ord(c) - ord('a')] if prev == c: count += 1 else: count = 1 prev = c if count > len(cur_record): cur_record.append(1) else: cur_record[count-1] += 1 max_len = -1 for j, record in enumerate(records): num = 0 for i in range(len(record) - 1, -1, -1): num += record[i] if num >= 3: max_len = max(i, max_len) return max_len + 1 if max_len != -1 else -1 ```
0
0
['Python3']
0
find-longest-special-substring-that-occurs-thrice-i
Diff Array Approach Time Complexity O(n) Space Complexity O(n)
diff-array-approach-time-complexity-on-s-xx8t
IntuitionThis is a more generic solution, that detects any subtring that occurs for k times. It is hard coded as three for this solution. The idea is that for e
stanlearningcoding
NORMAL
2025-03-06T06:23:05.232921+00:00
2025-03-06T06:23:05.232921+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> This is a more generic solution, that detects any subtring that occurs for k times. It is hard coded as three for this solution. The idea is that for each continuous character, if we want to count number of occurence of embedded substring, we can use the diff array. for example, we have continuous array length 3, then we can have array [1, 1, 1] the index is length -1. and we have 3 substrings of length 1, and 2 substrings of length 2, and 1 substring of length 3. And this information could be reconstructed if we do prefix sum from right to left. so each time when we see an element, we update the diff array based on the length of current continuous substring. see if we have length 2, we want to increment the diff array [1] by 1 # Approach <!-- Describe your approach to solving the problem. --> code explains itself hopefully # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) the string is iterated once, and the record 2d array is iterated once - Space complexity: O(1) bounded by 50 * 26 # Code ```python3 [] class Solution: def maximumLength(self, s: str) -> int: records = [[] for _ in range(26)] max_count = [0 for _ in range(26)] prev = -1 count = 0 for c in s: cur_record = records[ord(c) - ord('a')] if prev == c: count += 1 else: count = 1 prev = c if count > len(cur_record): cur_record.append(1) else: cur_record[count-1] += 1 max_len = -1 for j, record in enumerate(records): num = 0 for i in range(len(record) - 1, -1, -1): num += record[i] if num >= 3: max_len = max(i, max_len) return max_len + 1 if max_len != -1 else -1 ```
0
0
['Python3']
0
find-longest-special-substring-that-occurs-thrice-i
O(N) python solution
on-python-solution-by-miaolin-bkj1
Approach cnt keeps counting continuous chars prev. dic keeps { special_substring : cnt } mapping When we found count for char prev, we update dic for prev* cnt,
miaolin
NORMAL
2025-02-28T23:54:33.187427+00:00
2025-02-28T23:54:33.187427+00:00
1
false
# Approach * `cnt` keeps counting continuous chars `prev`. * `dic` keeps { special_substring : cnt } mapping When we found count for char prev, we update dic for prev* cnt, prev*(cnt-1), prev*(cnt-2). e.g., for "aaaa", `dic["aaaa"]+=1, dic["aaa"]+=2, dic["aa"]+=3` <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def maximumLength(self, s: str) -> int: dic = defaultdict(int) res = -1 cnt, prev = 0, "#" for i, char in enumerate(s+"#"): if char == prev: cnt += 1 else: dic[prev*cnt] += 1 dic[prev*(cnt-1)] += 2 if cnt > 1 else 0 dic[prev*(cnt-2)] += 3 if cnt > 2 else 0 res = max(res, cnt) if dic[prev*cnt]>= 3 else res res = max(res, cnt-1) if dic[prev*(cnt-1)] >= 3 else res res = max(res, cnt-2) if dic[prev*(cnt-2)] >= 3 else res prev, cnt = char, 1 return res ```
0
0
['Hash Table', 'String', 'Python3']
0
find-longest-special-substring-that-occurs-thrice-i
Longest special substring occurring thrice, using a Map-based approach
longest-special-substring-occurring-thri-yd6f
IntuitionI immediately thought some sort of mapping would be useful, but I didn't immediately know what I wanted to create a mapping of. It became clear that ha
fHIBox8sPF
NORMAL
2025-02-19T01:28:33.548656+00:00
2025-02-19T01:28:33.548656+00:00
2
false
# Intuition I immediately thought some sort of mapping would be useful, but I didn't immediately know what I wanted to create a mapping of. It became clear that having separate counts corresponding to each character would end up being useful, so I ended up doing those. # Approach I ultimately decided it would be useful to collect a mapping of each character to all the special string lengths beginning with that character. As I started writing the code, I had an insight that in processing this map to determine the final result, the longest special string for each character could now be obtained by just getting the third-largest number from the sorted list since each number preceding a bigger number definitionally fits into the bigger number (e.g., a string of 7 a's of course can be found in a string of 8 a's, which would necessarily mean these constitute 2 occurrences of 7). So getting the final result is just a matter of grabbing this number from each sorted list and getting the biggest of those numbers. There are some small optimizations that could still be done, such as inserting in sorted order when adding lengths to the arrays and perhaps keeping the sorting instead in a descending order since the counts within a broader special string will only go down for the remainder of that particular special string, but this solution has already proven to be very efficient as is given the runtime metrics, so I didn't really bother with those small additions. # Complexity - Time complexity: - getSpecialSubstringLength() counts up to $n - 1$ characters: $O(n)$ - First loop iterates s: $$O(n)$$ - Each iteration calls getSpecialSubstringLength() once: O(n) - Overall: $O(n^2)$ to produce map of characters to special lengths for each character - Second loop iterates specialLengths map, which scales linearly with s, but our worst case scenario of just 1 constantly repeated character will mean there's only 1 iteration: $O(n)$ - Each array is sorted: $O(n logn)$ - Overall: $O(n logn)$ because the sorts are on subsections of at most n counts when taken altogether - $O(n^2)$ - Space complexity: - Map uses $O(n)$ space since we add a count for every character - $O(n)$ # Code ```typescript [] function getSpecialSubstringLength(s: string, index: number): number { const specialChar = s[index]; let count = 1; for (let i = index + 1; i < s.length; i++) { if (s[i] !== specialChar) break; count++; } return count; } function maximumLength(s: string): number { const specialLengths = new Map<string, number[]>(); for (let i = 0; i < s.length; i++) { const c = s[i]; if (!specialLengths.get(c)) { specialLengths.set(c, []); } specialLengths.get(c).push(getSpecialSubstringLength(s, i)); } let longestThriceSpecialStr = -1; for (const [, strLengths] of specialLengths.entries()) { if (strLengths.length < 3) continue; const sortedStrLengths = strLengths.sort((a, b) => a - b); // Third highest number is longest special substring // For instance, consider: [1, 2, 5, 6, 7, 9] // 6 necessarily fits into 7 and 9 due to sorting const longestThriceStrForChar = sortedStrLengths[strLengths.length - 3]; if (longestThriceStrForChar > longestThriceSpecialStr) { longestThriceSpecialStr = longestThriceStrForChar; } } return longestThriceSpecialStr; }; ```
0
0
['TypeScript']
0
find-longest-special-substring-that-occurs-thrice-i
Easy C++ Hash map + brute force
easy-c-hash-map-brute-force-by-domainame-whw9
IntuitionApproachComplexity Time complexity: Space complexity: Code
Domainame
NORMAL
2025-02-12T21:38:08.363659+00:00
2025-02-12T21:38:08.363659+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maximumLength(string s) { unordered_map<char, int> m1; int ans = -1; //construct alphbet numbers for(auto c : s){ m1[c]++; } //if character larger than three can form a thrice for(auto[key, ch] : m1){ if(ch >= 3){ int window = ch ; ans = max(ans, 1); //start from max possible window ; while(window >= 1){ string tmp =""; int count = 0; for(int i=0;i<window;++i){ tmp += key; } //iterate through substr check for(int j=0; j < s.size() - window + 1; ++j) { if(s.substr(j, window) == tmp){ count++; } } if (count >= 3){ ans = max(ans, window); } window--; } } } return ans; } }; ```
0
0
['Hash Table', 'String', 'Sliding Window', 'Counting', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
A C Solution
a-c-solution-by-well_seasoned_vegetable-n7z8
Not entirely a solution that utilises data structures and algorithms to solve the problem optimally or one that has clean code but just some strangely functiona
well_seasoned_vegetable
NORMAL
2025-02-10T14:54:49.082669+00:00
2025-02-10T14:55:00.612508+00:00
1
false
Not entirely a solution that utilises data structures and algorithms to solve the problem optimally or one that has clean code but just some strangely functional logic # Logic 1. Let any new max special substring length be tLen 2. For any tLen >= 3, the new longest special substring that appears thrice is tLen - 2 (since a substring of length tLen - 2 can appear 3 times in a substring of length tLen) eg for tLen = 5: (aaa)aa a(aaa)a aa(aaa) 3. Point 2. always holds for new tLens that have no previous tLens yet 4. If there is a previous tLen, for example oldLen (which would now be the second largest substring length, the first being tLen), we have to consider: a. What is the difference between oldLen and tLen? b. If the difference is 1, then oldLen which is larger than tLen - 2, would be the new max, since it would have appeared thrice, eg oldLen = 4, (aaaa), tLen = 5, (aaaa)a, a(aaaa) c. If the difference is more than or equal to 2, then it does not matter and tLen - 2 is still the new longest special substring that appears thrice 5. Similar to Point 4. if you encounter a special substring that is of length tLen - 1, then the special substring tLen - 1 would have appeared thrice as well 6. Similar to Points 4. and 5., if tLen appears twice, then the longest special substring that appears thrice would also be tLen - 1 since each occurence of tLen accomodates 2 instances of substrings of length tLen - 1, which amounts to 4 occurences, which is more than three 7. Lastly, the final case of a unique substring appearing thrice would of course be the the unqiue substring literally occurring thrice, aka finding tLen of a char 3 times, which is why the counters are still required 8. We can conclude that for every letter, we only have to store: a. The longest special substring for that char so far aka tLen b. The number of times the longest substring for that char so far has appeared Since the other cases of the return value can be based off of tLen # Code ```c [] int maximumLength(char* s) { int map[26][2] = {0}; int len = strlen(s); int max = -1, i = 0; while(i < len) { int curr = i; for(; i < len; i++) { if(s[curr] != s[i]) break; } int tLen = i - curr; int c = s[curr] - 'a'; if(!map[c][0]) { map[c][0] = tLen; map[c][1] = 1; if(tLen >= 3) max = max > (tLen - 2)? max : (tLen - 2); } else { if(map[c][0] - tLen == 1) max = max > tLen? max : tLen; else if(tLen < map[c][0]) continue; else if(tLen == map[c][0]) { ++map[c][1]; if(map[c][0] > 1 && map[c][1] == 2) max = max > (map[c][0] - 1)? max : (map[c][0] - 1); else if(map[c][1] == 3) max = max > map[c][0]? max : map[c][0]; } else { if(tLen - map[c][0] == 1) max = max > map[c][0]? max : map[c][0]; else max = max > (tLen - 2)? max : (tLen - 2); map[c][0] = tLen; map[c][1] = 1; } } } return max; } ```
0
0
['C']
0
find-longest-special-substring-that-occurs-thrice-i
Brute Force approach to generate substrings and storing in hashmap.
brute-force-approach-to-generate-substri-20ie
IntuitionBrute force all combinations since the constraints are small. Apply two pointer to generate substrings and kind of a sliding window approach.ApproachCo
sahassaxena123
NORMAL
2025-02-10T11:22:15.444798+00:00
2025-02-10T11:22:15.444798+00:00
3
false
# Intuition Brute force all combinations since the constraints are small. Apply two pointer to generate substrings and kind of a sliding window approach. # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maximumLength(String s) { HashMap<String, Integer> h = new HashMap<>(); int n = s.length(); String temp = ""; int i = 0, j = 0; while( i < n ) { if(i < n && j < n && s.charAt(i) == s.charAt(j)) { temp = temp + String.valueOf(s.charAt(j)); h.put(temp, h.getOrDefault(temp, 0) + 1); j++; } else { temp = ""; while(i != j) { String sub = ""; for(int k = i + 1; k < j; k++) { sub = sub + s.charAt(k); h.put(sub, h.getOrDefault(sub, 0) + 1); } i++; } } } // System.out.println(h); int ans = 0; for(String key : h.keySet()) { if(h.get(key) >= 3) { ans = Math.max(ans, key.length()); } } return (ans>0) ? ans : -1; } } ```
0
0
['Java']
0
find-longest-special-substring-that-occurs-thrice-i
Beats 98% proficiency.
beats-98-proficiency-by-e6sfuhi04s-8nzp
IntuitionApproachComplexity Time complexity: Space complexity: Code
S4LIL_P4TEL
NORMAL
2025-02-05T05:59:02.340842+00:00
2025-02-05T05:59:02.340842+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] public class Solution { public int maximumLength(String s) { int n = s.length(); int l = 1, r = n; if (!helper(s, n, l)) return -1; while (l + 1 < r) { int mid = (l + r) / 2; if (helper(s, n, mid)) l = mid; else r = mid; } return l; } private boolean helper(String s, int n, int x) { int[] cnt = new int[26]; int p = 0; for (int i = 0; i < n; i++) { while (s.charAt(p) != s.charAt(i)) p++; if (i - p + 1 >= x) cnt[s.charAt(i) - 'a']++; if (cnt[s.charAt(i) - 'a'] > 2) return true; } return false; } } ```
0
0
['Java']
0
top-k-frequent-elements
Java O(n) Solution - Bucket Sort
java-on-solution-bucket-sort-by-mo10-p6sx
Idea is simple. Build a array of list to be buckets with length 1 to sort.\n\n public List topKFrequent(int[] nums, int k) {\n\n\t\tList[] bucket = new List[
mo10
NORMAL
2016-05-02T04:09:19+00:00
2018-10-23T19:51:59.118501+00:00
279,055
false
Idea is simple. Build a array of list to be buckets with length 1 to sort.\n\n public List<Integer> topKFrequent(int[] nums, int k) {\n\n\t\tList<Integer>[] bucket = new List[nums.length + 1];\n\t\tMap<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();\n\n\t\tfor (int n : nums) {\n\t\t\tfrequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);\n\t\t}\n\n\t\tfor (int key : frequencyMap.keySet()) {\n\t\t\tint frequency = frequencyMap.get(key);\n\t\t\tif (bucket[frequency] == null) {\n\t\t\t\tbucket[frequency] = new ArrayList<>();\n\t\t\t}\n\t\t\tbucket[frequency].add(key);\n\t\t}\n\n\t\tList<Integer> res = new ArrayList<>();\n\n\t\tfor (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {\n\t\t\tif (bucket[pos] != null) {\n\t\t\t\tres.addAll(bucket[pos]);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}
1,315
19
[]
167
top-k-frequent-elements
3 Java Solution using Array, MaxHeap, TreeMap
3-java-solution-using-array-maxheap-tree-ki57
// use an array to save numbers into different bucket whose index is the frequency\n public class Solution {\n public List<Integer> topKFrequent(int[]
upthehell
NORMAL
2016-06-14T14:58:48+00:00
2018-10-21T06:40:29.363188+00:00
156,188
false
// use an array to save numbers into different bucket whose index is the frequency\n public class Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n for(int n: nums){\n map.put(n, map.getOrDefault(n,0)+1);\n }\n \n // corner case: if there is only one number in nums, we need the bucket has index 1.\n List<Integer>[] bucket = new List[nums.length+1];\n for(int n:map.keySet()){\n int freq = map.get(n);\n if(bucket[freq]==null)\n bucket[freq] = new LinkedList<>();\n bucket[freq].add(n);\n }\n \n List<Integer> res = new LinkedList<>();\n for(int i=bucket.length-1; i>0 && k>0; --i){\n if(bucket[i]!=null){\n List<Integer> list = bucket[i]; \n res.addAll(list);\n k-= list.size();\n }\n }\n \n return res;\n }\n }\n \n \n \n // use maxHeap. Put entry into maxHeap so we can always poll a number with largest frequency\n public class Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n for(int n: nums){\n map.put(n, map.getOrDefault(n,0)+1);\n }\n \n PriorityQueue<Map.Entry<Integer, Integer>> maxHeap = \n new PriorityQueue<>((a,b)->(b.getValue()-a.getValue()));\n for(Map.Entry<Integer,Integer> entry: map.entrySet()){\n maxHeap.add(entry);\n }\n \n List<Integer> res = new ArrayList<>();\n while(res.size()<k){\n Map.Entry<Integer, Integer> entry = maxHeap.poll();\n res.add(entry.getKey());\n }\n return res;\n }\n }\n \n \n \n // use treeMap. Use freqncy as the key so we can get all freqencies in order\n public class Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n for(int n: nums){\n map.put(n, map.getOrDefault(n,0)+1);\n }\n \n TreeMap<Integer, List<Integer>> freqMap = new TreeMap<>();\n for(int num : map.keySet()){\n int freq = map.get(num);\n if(!freqMap.containsKey(freq)){\n freqMap.put(freq, new LinkedList<>());\n }\n freqMap.get(freq).add(num);\n }\n \n List<Integer> res = new ArrayList<>();\n while(res.size()<k){\n Map.Entry<Integer, List<Integer>> entry = freqMap.pollLastEntry();\n res.addAll(entry.getValue());\n }\n return res;\n }\n }
435
6
['Array', 'Tree', 'Heap (Priority Queue)', 'Java']
57
top-k-frequent-elements
【Video】2 solutions
video-2-solutions-by-niits-e8up
Intuition\nUsing heap or array.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/KzpgnqoB43c\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my chan
niits
NORMAL
2024-07-21T18:15:51.120331+00:00
2024-08-31T06:05:15.990696+00:00
48,049
false
# Intuition\nUsing `heap` or `array`.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/KzpgnqoB43c\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 6,683\nThank you for your support!\n\n---\n\n# Approach\n\nI\'ll show you two ways to solve this question.\n\n# Solution 1\n\n```\nInput: nums = [10,10,20,20,20,30], k = 2\n```\n\nWe have to return `Top K Frequent Elements`, so if we have frequency of each number, we can return numbers easily.\n\nTo do that, I use `heap`.\n\nFirst of all, we count frequency of each number.\n\n```\n20 \u2192 3 times\n10 \u2192 2 times\n30 \u2192 1 time\n```\nNext we use `heap` and we want to keep 2 numbers so use `tuple` in heap.\n```\n(frequency, number)\n(3, 20)\n(2, 10)\n(1, 30)\n```\n\n---\n\n* Problem\n\nProblem here is in Python `heap` is usually `min heap`, so if we pop data from `heap`, we will get `(1, 30)` at first. Next time we will get `(2, 10)`.\n\nBut we want `(3, 20)` at first. Next time we want `(2, 10)`.\n\n---\n\n### How can we solve the problem?\n\nMy strategy is when we add tuples to `heap`, we add `negative` to all frequency, so **that maximum frequency will be minimum number.**\n\nFor example,\n```\n(3, 20) \u2192 (-3, 20)\n(2, 10) \u2192 (-2, 10)\n(1, 30) \u2192 (-1, 30)\n```\nIf we add negative to all frequency, `min heap` will work as a `max heap`.\n\nNow `heap` has\n```\n(-3, 20)\n(-2, 10)\n(-1, 30)\n```\nJust pop data `k` times. We will get `(-3, 20)` at first.\n\n```\nres = [20]\n\nheap has\n(-2, 10)\n(-1, 30)\n```\nNext, we will get `(-2, 10)`.\n\n```\nres = [20, 10]\n\nheap has\n(-1, 30)\n```\nNow, length of `res` is equal to `k`.\n\n```\nreturn [20, 10]\n```\n\nEasy!\uD83D\uDE04\nLet\'s see solution codes!\n\n---\n\nhttps://youtu.be/bU_dXCOWHls\n\n---\n\n# Complexity\n- Time complexity: $$O(n log k)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n heap = []\n counter = {}\n for n in nums:\n counter[n] = 1 + counter.get(n, 0)\n \n for key, val in counter.items():\n heapq.heappush(heap, (-val, key))\n \n res = []\n while len(res) < k:\n res.append(heapq.heappop(heap)[1])\n \n return res\n```\n```java []\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> counter = new HashMap<>();\n for (int n : nums) {\n counter.put(n, counter.getOrDefault(n, 0) + 1);\n }\n \n PriorityQueue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(\n (a, b) -> Integer.compare(b.getValue(), a.getValue())\n );\n \n for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {\n heap.offer(entry);\n }\n \n int[] res = new int[k];\n for (int i = 0; i < k; i++) {\n res[i] = Objects.requireNonNull(heap.poll()).getKey();\n }\n \n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> counter;\n for (int n : nums) {\n counter[n]++;\n }\n \n auto comp = [](pair<int, int>& a, pair<int, int>& b) {\n return a.second < b.second;\n };\n priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> heap(comp);\n \n for (auto& entry : counter) {\n heap.push({entry.first, entry.second});\n }\n \n vector<int> res;\n while (k-- > 0) {\n res.push_back(heap.top().first);\n heap.pop();\n }\n \n return res; \n }\n};\n```\n\n# Step by Step Algorithm\n\n1. **Initialize Data Structures**\n\n ```python\n heap = []\n counter = {}\n ```\n\n - **`heap`**: A list that will be used as a priority queue to store elements based on their frequencies. Python\u2019s `heapq` module provides a min-heap, so we\'ll store negative frequencies to simulate a max-heap.\n - **`counter`**: A dictionary to count the frequency of each element in the `nums` list.\n\n2. **Count Frequencies**\n\n ```python\n for n in nums:\n counter[n] = 1 + counter.get(n, 0)\n ```\n\n - **`counter[n] = 1 + counter.get(n, 0)`**: Iterate through each number `n` in `nums` and update its frequency in the `counter` dictionary. If `n` is not already in `counter`, `counter.get(n, 0)` returns 0, so `counter[n]` becomes 1. If `n` is already in `counter`, it increments its count by 1.\n\n3. **Build the Heap**\n\n ```python\n for key, val in counter.items():\n heapq.heappush(heap, (-val, key))\n ```\n\n - **`heapq.heappush(heap, (-val, key))`**: Iterate through the `counter` dictionary and push each element into the heap. The `heapq.heappush` function adds elements to the heap and maintains the heap property. By storing `-val` (negative frequency), we simulate a max-heap behavior using Python\u2019s min-heap. The heap will prioritize elements with higher frequencies because of the negative sign.\n\n4. **Extract Top K Frequent Elements**\n\n ```python\n res = []\n while len(res) < k:\n res.append(heapq.heappop(heap)[1])\n ```\n\n - **`res`**: Initialize an empty list to store the top `k` frequent elements.\n - **`heapq.heappop(heap)`**: Pop the smallest element from the heap (which is the one with the highest frequency due to the negative sign). The `[1]` retrieves the actual element (not its frequency) from the tuple `(-val, key)`.\n - **`while len(res) < k`**: Continue extracting elements from the heap until we have `k` elements in `res`.\n\n5. **Return Result**\n\n ```python\n return res\n ```\n\n - **Return `res`**: Once the loop completes and `res` contains the top `k` frequent elements, return `res`.\n\n\n---\n\n# Solution 2\n\nIt\'s similar to `solution 1` to count frequency of each number.\n\n```\nInput: nums = [10,10,20,20,20,30], k = 2\n```\n```\n20 \u2192 3 times\n10 \u2192 2 times\n30 \u2192 1 time\n```\nCreate `array` with `length of input + 1`. We use index numbers as frequency. For instance, `3 times` goes to `index 3`.\n\n```\nindex 0, 1, 2, 3,4,5,6\nfreq = [ ,30, 10, 20, , , ]\n```\n\nAll we have to do is just iterate through from end, **because as I told you, we use index numbers as frequency and we have to return top K frequency element, so if we check numbers from the end, we will get top k numbers.**\n\nIn this case, there is no number at index `6`, `5` and `4`. Then we find `20` at index `3`.\n\n```\nres = [20]\n```\nAt index `2`, we find `10`.\n\n```\nres = [20, 10]\n```\nNow, length of `res` is equal to `k`.\n\n```\nreturn [20, 10]\n```\n\nLet me add two points.\n\n##### Why we created array with length of input + 1?\n\nImagine all numbers in input array is `10`.\n\n```\nInput: nums = [10,10,10,10,10,10], k = 2\n```\nIn this case, we have `six 10`. They go to index `6`. But what if we create `array` with the same length of input?\n\n```\nindex 0,1,2,3,4,5\nres = [ , , , , , ]\n```\nThere is no index `6`. We will get `out of bounds`.\n\n- Why this happened?\n\nThat\'s because index number usually starts from `0` and frequency of each number starts from `1`. There is `1` difference. That\'s why we need to prepare for `+1 length`.\n\n##### What if we have different numbers with the same frequency?\n\nYes, there is possibility that we have different numbers with the same frequency.\n\nFor example,\n```\nInput: nums = [10,20,10,20,30,40], k = 2\n```\nIn this case, `30` and `40` go to index `1`. `10` and `20` go to index `2`. That\'s why we have array in each index of `res`, so that we can keep multiple numbers at the same index.\n\n```\nres = [[],[30,40],[10,20],[],[],[],[]]\n```\n\n```\nreturn [10, 20] or [20, 10]\n```\nThe description says "You may return the answer in any order."\n\nEasy!\uD83D\uDE04\nLet\'s see solution codes!\n\n---\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n counter = {}\n\n for n in nums:\n counter[n] = 1 + counter.get(n, 0)\n \n freq = [[] for _ in range(len(nums) + 1)]\n\n for n, f in counter.items():\n freq[f].append(n)\n \n res = []\n\n for i in range(len(freq) - 1, -1, -1):\n for n in freq[i]:\n res.append(n)\n if len(res) == k:\n return res\n```\n```java []\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> counter = new HashMap<>();\n for (int n : nums) {\n counter.put(n, counter.getOrDefault(n, 0) + 1);\n }\n \n List<Integer>[] freq = new ArrayList[nums.length + 1];\n for (int i = 0; i < freq.length; i++) {\n freq[i] = new ArrayList<>();\n }\n \n for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {\n int frequency = entry.getValue();\n freq[frequency].add(entry.getKey());\n }\n \n int[] res = new int[k];\n int idx = 0;\n for (int i = freq.length - 1; i >= 0; i--) {\n for (int num : freq[i]) {\n res[idx++] = num;\n if (idx == k) {\n return res;\n }\n }\n }\n \n return new int[0]; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> counter;\n for (int n : nums) {\n counter[n]++;\n }\n \n vector<vector<int>> freq(nums.size() + 1);\n for (auto& entry : counter) {\n freq[entry.second].push_back(entry.first);\n }\n \n vector<int> res;\n for (int i = freq.size() - 1; i >= 0; i--) {\n for (int num : freq[i]) {\n res.push_back(num);\n if (res.size() == k) {\n return res;\n }\n }\n }\n \n return {}; \n }\n};\n```\n\n# Step by Step Algorithm\n\n1. **Initialize the Counter Dictionary**\n\n ```python\n counter = {}\n ```\n\n - **`counter`**: A dictionary to count the frequency of each element in the `nums` list.\n\n2. **Count Frequencies**\n\n ```python\n for n in nums:\n counter[n] = 1 + counter.get(n, 0)\n ```\n\n - **`counter[n] = 1 + counter.get(n, 0)`**: Iterate through each number `n` in `nums` and update its frequency in the `counter` dictionary. If `n` is not already in `counter`, `counter.get(n, 0)` returns 0, so `counter[n]` becomes 1. If `n` is already in `counter`, it increments its count by 1.\n\n3. **Initialize the Frequency Buckets**\n\n ```python\n freq = [[] for _ in range(len(nums) + 1)]\n ```\n\n - **`freq`**: A list of lists where the index represents the frequency, and the value at each index is a list of numbers with that frequency. The length is `len(nums) + 1` because the maximum frequency of any number cannot exceed the length of the list `nums`.\n\n4. **Fill the Frequency Buckets**\n\n ```python\n for n, f in counter.items():\n freq[f].append(n)\n ```\n\n - **`for n, f in counter.items()`**: Iterate through the `counter` dictionary.\n - **`freq[f].append(n)`**: Append the number `n` to the list at index `f` in the `freq` list. This groups numbers by their frequencies.\n\n5. **Collect Top K Frequent Elements**\n\n ```python\n res = []\n ```\n\n - **`res`**: Initialize an empty list to store the top `k` frequent elements.\n\n6. **Traverse the Frequency Buckets in Reverse Order**\n\n ```python\n for i in range(len(freq) - 1, -1, -1):\n for n in freq[i]:\n res.append(n)\n if len(res) == k:\n return res\n ```\n\n - **`for i in range(len(freq) - 1, -1, -1)`**: Iterate through the `freq` list from the highest frequency to the lowest (reverse order).\n - **`for n in freq[i]`**: For each frequency bucket, iterate through the list of numbers.\n - **`res.append(n)`**: Append the number `n` to the `res` list.\n - **`if len(res) == k`**: Check if the size of the `res` list is equal to `k`. If true, return the `res` list immediately.\n\n7. **Return Result**\n\n ```python\n return res\n ```\n\n - **Return `res`**: Once the loop completes and `res` contains the top `k` frequent elements, return `res`.\n\n---\n\n# Bonus\n\nI guess we can\'t use this in real interview, but we can solve this question like this.\n\n```python []\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n return [x for x, y in Counter(nums).most_common(k)]\n```\n\n---\n\nThank you for reading my post. Please upvote it and don\'t forget to subscribe to my channel!\n\n\u2B50\uFE0F Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u2B50\uFE0F Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n\u2B50\uFE0F My previous solution\n\nRemove Element - LeetCode #27\n\nhttps://youtu.be/GDOxAHN4RSE\n
344
0
['C++', 'Java', 'Python3']
12
top-k-frequent-elements
C++ O(n log(n-k)) unordered_map and priority_queue(maxheap) solution
c-on-logn-k-unordered_map-and-priority_q-e4kw
\n class Solution {\n public:\n vector topKFrequent(vector& nums, int k) {\n unordered_map map;\n for(int num : nums){\n
sxycwzwzq
NORMAL
2016-05-02T02:37:53+00:00
2018-10-25T08:06:31.849779+00:00
92,254
false
\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int> map;\n for(int num : nums){\n map[num]++;\n }\n \n vector<int> res;\n // pair<first, second>: first is frequency, second is number\n priority_queue<pair<int,int>> pq; \n for(auto it = map.begin(); it != map.end(); it++){\n pq.push(make_pair(it->second, it->first));\n if(pq.size() > (int)map.size() - k){\n res.push_back(pq.top().second);\n pq.pop();\n }\n }\n return res;\n }\n };
327
2
['C++']
54
top-k-frequent-elements
One OF THE best EXPLANATION
one-of-the-best-explanation-by-hi-malik-4ig4
How\'s going Ladies - n - Gentlemen, today we are going to solve another coolest problem i.e. Top K Frequent Elements\n\nOkay, so in order to solve this problem
hi-malik
NORMAL
2022-04-09T03:35:03.650892+00:00
2022-04-09T03:35:03.650934+00:00
33,270
false
How\'s going Ladies - n - Gentlemen, today we are going to solve another coolest problem i.e. **Top K Frequent Elements**\n\nOkay, so in order to solve this problem, first of all let\'s understand what the problem statement is:\n```\nGiven an integer array nums, \nand an integer k, return the k most frequent elements. You may return the answer in any order.\n```\n\nOkay, so wait wait listen just looking at this if you know the **HashMap**, you\'ll simply gonna say we can solve this problem easily using **HashMap**. And I\'ll say yes, exactly we gonna do the exact same thing but we will use **Heap** as well with **HashMap**, if you got the idea by listening **heap**. Then you had just solve the **`brute force approach`**\n\nSo, let\'s talk about it\'s \n```\nBrute Force Approach :-\n```\nLet\'s take an example,\n\n**Input**: nums = [1,1,1,2,2,3], k = 2\n**Output**: [1,2]\n\nSo, we have 2 step\'s to perform in this problem:-\n1. **HashMap**\n\n\n2. **Heap**\n\n**`Step -1 :-`** Make an Frequency map & fill it with the given elements\n```\n\t\t\t\t\t\t\t\t[1,1,1,2,2,3]\n\t\t\t\t\t\t\t\t\n\t\t------------------------------------------------\t\t\t\t\t\t\t\n\t\t\t| 1 ---> | 3 |\n\t\t\t| | |\n\t\t\t| 2 ---> | 2 | HashMap of Integer, Integer\n\t\t\t| | |\n\t\t\t| 3 ---> | 1 |\n\t\t------------------------------------------------\n```\nOkay, so we just had completed our step no.1 now, it;s time to move to next step\n\n**`Step -2 :-`** Make an **MaxHeap** & fill it with keys & on the peek of our Heap we will be having most frequent elements\n\n```\nHashMap :-\n\t\tKey Value\n\t\t1 ----> 3\n\t\t2 ----> 2\n\t\t3 ----> 1\n\t\t\nHeap :-\n\t\t\n\t\t| 1 | from the top of the heap we\'ll pop that no. of element requires in our array of k size\n\t\t| 2 |\n\t\t| 3 |\n\t ------------\n```\nCreate result array **`res`** & store K frequent elements in it.\n```\nHeap :-\n\t\t\n\t\t| | res : [1]\n\t\t| 2 |\n\t\t| 3 |\n\t ------------\n```\n\n```\nHeap :-\n\t\t\n\t\t| | res : [1, 2]\n\t\t| |\n\t\t| 3 |\n\t ------------\n```\nAs, our K is 2 we gonna only store Most frequent K elements in our array, therefore in the result we get:- **`[1, 2]`**\n\nI hope so, ladies - n - gentlemen, this approach is absolute clear, **Let\'s code it, up**\n\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n \n for(int i : nums){\n map.put(i, map.getOrDefault(i, 0) + 1);\n }\n \n PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b) -> map.get(b) - map.get(a));\n \n for(int key : map.keySet()){\n maxHeap.add(key);\n }\n \n int res[] = new int[k];\n for(int i = 0; i < k; i++){\n res[i] = maxHeap.poll();\n }\n return res;\n }\n}\n```\nANALYSIS :-\n* **Time Complexity :-** BigO(K log D) as we are Poll K distinct elements from the Heap & here D is no. of distinct (unique) elements in the input array\n\n* **Space Complexity :-** BigO(D), this is the size of the heap.\n\nWell, this is not a super efficient Approach,\nWe can solve this more efficiently as well, now some of you\'ll ask but how!!\n\nWell, for that we have **Bucket Sorting**\n\n```\nOptimize Approach :-\n```\n\nLet\'s understand what bucket sort is,\n\n**Bucket sort, or bin sort**, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.\n\nIn this process we gonna follow 3 major steps :-\n\n**`Step - 1 :`**\n*Create Frequency map:*\n1.1 Iterate thru the given nums[] array\n1.2. With each iteration - check if map already contains current key\nIf current key is already in the map just increase the value for this key\nElse add key value pair.\nWhere key is current int and value is 1 (1 -> we encounter given key for the first time)\n\n![image](https://assets.leetcode.com/users/images/fc83428e-498e-4279-9c15-ed05d7acdad5_1649473998.719139.png)\n\n**`Step - 2 :`**\n*Create Bucket List[]:*\nindex of bucket[] arr will represent the value from our map\nWhy not use int[] arr? Multiple values can have the same frequency that\'s why we use List[] array of lists instead of regular array\nIterate thrue the map and for each value add key at the index of that value\n\n![image](https://assets.leetcode.com/users/images/9f207290-a760-4cde-90d0-b108e0f0ea09_1649474879.6786613.png)\n\n**`Step - 3 :`**\nIf we look at bucket arr we can see that most frequent elements are located at the end of arr\nand leat frequent elemnts at the begining\nLast step is to iterate from the end to the begining of the arr and add elements to result List\n\n![image](https://assets.leetcode.com/users/images/65c0d64e-ecd8-480d-a710-d47a7c61283a_1649475206.9108236.png)\n\nI hope so ladies - n - gentlemen Approach is absolute clear, **Let\'s code it up**\n\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n \n for(int i : nums){\n map.put(i, map.getOrDefault(i, 0) + 1);\n }\n \n List<Integer> bucket[] = new ArrayList[nums.length + 1];\n \n for(int key : map.keySet()){\n int freq = map.get(key);\n if(bucket[freq] == null){\n bucket[freq] = new ArrayList<>();\n }\n bucket[freq].add(key);\n }\n \n int res[] = new int[k];\n int index = 0;\n for(int i = bucket.length - 1; i >= 0; i--){\n if(bucket[i] != null){\n for(int val : bucket[i]){\n res[index++] = val;\n if(index == k) return res;\n }\n }\n }\n return res;\n }\n}\n```\nANALYSIS :-\n* **Time Complexity :-** BigO(N)\n\n* **Space Complexity :-** BigO(N)
307
4
[]
20
top-k-frequent-elements
3 ways to solve this problem
3-ways-to-solve-this-problem-by-robin8-ieqx
using heap\n\n class Solution {\n public:\n vector topKFrequent(vector& nums, int k) {\n priority_queue, vector\>, greater\>> pq;\n
robin8
NORMAL
2016-05-02T21:58:13+00:00
2018-10-18T10:46:32.885331+00:00
84,924
false
using heap\n\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n unordered_map<int, int> cnt;\n for (auto num : nums) cnt[num]++;\n for (auto kv : cnt) {\n pq.push({kv.second, kv.first});\n while (pq.size() > k) pq.pop();\n }\n vector<int> res;\n while (!pq.empty()) {\n res.push_back(pq.top().second);\n pq.pop();\n }\n return res;\n }\n };\n\n\nusing selection algorithm\n\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n vector<int> res;\n if (!nums.size()) return res;\n unordered_map<int, int> cnt;\n for (auto num : nums) cnt[num]++;\n vector<pair<int, int>> num_with_cnt;\n for (auto kv : cnt) {\n num_with_cnt.push_back({kv.first, kv.second});\n }\n kselection(num_with_cnt, 0, num_with_cnt.size()-1, k);\n for (int i = 0; i < k && i < num_with_cnt.size(); ++i) {\n res.push_back(num_with_cnt[i].first);\n }\n return res;\n }\n \n void kselection(vector<pair<int, int>>& data, int start, int end, int k) {\n \n if (start >= end) return;\n auto pv = data[end];\n int i = start;\n int j = start;\n while (i < end) {\n if (data[i].second > pv.second) {\n swap(data[i++], data[j++]);\n } else {\n ++i;\n }\n }\n swap(data[j], data[end]);\n int num = j - start + 1;\n if (num == k) return;\n else if (num < k) {\n kselection(data, j + 1, end, k - num);\n } else {\n kselection(data, start, j - 1, k);\n }\n }\n };\n\n\nusing bucket sort\n\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n vector<int> res;\n if (!nums.size()) return res;\n unordered_map<int, int> cnt;\n for (auto num : nums) cnt[num]++;\n vector<vector<int>> bucket(nums.size() + 1);\n for (auto kv : cnt) {\n bucket[kv.second].push_back(kv.first);\n }\n \n for (int i = bucket.size() - 1; i >= 0; --i) {\n for (int j = 0; j < bucket[i].size(); ++j){\n res.push_back(bucket[i][j]);\n if (res.size() == k) return res;\n }\n }\n \n return res;\n }\n };
184
3
[]
29
top-k-frequent-elements
Python O(n) solution without sort, without heap, without quickselect
python-on-solution-without-sort-without-2m6ta
\nclass Solution(object):\n def topKFrequent(self, nums, k):\n hs = {}\n frq = {}\n for i in xrange(0, len(nums)):\n if nums[
rtom09
NORMAL
2016-12-22T09:41:51.527000+00:00
2018-10-21T22:04:20.685575+00:00
69,697
false
```\nclass Solution(object):\n def topKFrequent(self, nums, k):\n hs = {}\n frq = {}\n for i in xrange(0, len(nums)):\n if nums[i] not in hs:\n hs[nums[i]] = 1\n else:\n hs[nums[i]] += 1\n\n for z,v in hs.iteritems():\n if v not in frq:\n frq[v] = [z]\n else:\n frq[v].append(z)\n \n arr = []\n \n for x in xrange(len(nums), 0, -1):\n if x in frq:\n \n for i in frq[x]:\n arr.append(i)\n\n return [arr[x] for x in xrange(0, k)]\n```
175
7
['Array', 'Python']
33
top-k-frequent-elements
JavaScript No Sorting O(N) Time
javascript-no-sorting-on-time-by-control-gry2
javascript\nvar topKFrequent = function(nums, k) {\n const freqMap = new Map();\n const bucket = [];\n const result = [];\n \n for(let num of num
control_the_narrative
NORMAL
2020-06-04T09:12:43.453106+00:00
2020-07-15T03:52:16.181100+00:00
23,242
false
```javascript\nvar topKFrequent = function(nums, k) {\n const freqMap = new Map();\n const bucket = [];\n const result = [];\n \n for(let num of nums) {\n freqMap.set(num, (freqMap.get(num) || 0) + 1);\n }\n \n for(let [num, freq] of freqMap) {\n bucket[freq] = (bucket[freq] || new Set()).add(num);\n }\n \n for(let i = bucket.length-1; i >= 0; i--) {\n if(bucket[i]) result.push(...bucket[i]);\n if(result.length === k) break;\n }\n return result;\n};\n```
159
2
['JavaScript']
21
top-k-frequent-elements
Simple C++ solution using hash table and bucket sort
simple-c-solution-using-hash-table-and-b-nhma
class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> m;\n for (int num :
aeonaxx
NORMAL
2016-05-03T03:10:30+00:00
2018-10-15T04:49:10.491999+00:00
27,738
false
class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> m;\n for (int num : nums)\n ++m[num];\n \n vector<vector<int>> buckets(nums.size() + 1); \n for (auto p : m)\n buckets[p.second].push_back(p.first);\n \n vector<int> ans;\n for (int i = buckets.size() - 1; i >= 0 && ans.size() < k; --i) {\n for (int num : buckets[i]) {\n ans.push_back(num);\n if (ans.size() == k)\n break;\n }\n }\n return ans;\n }\n };
151
1
[]
18
top-k-frequent-elements
[C++/Python] 2 solutions: MaxHeap, Bucket Sort - Clean & Concise
cpython-2-solutions-maxheap-bucket-sort-gnmv5
\u2714\uFE0F Solution 1: Max Heap\n\n\n\nComplexity\n- Time: O(N + KlogN), where N <= 10^5 is length of nums array, K <= N.\n\t- heapify(maxHeap) costs O(N)\n\t
hiepit
NORMAL
2021-10-04T06:27:00.181334+00:00
2024-04-24T22:22:40.843433+00:00
10,670
false
**\u2714\uFE0F Solution 1: Max Heap**\n\n<iframe src="https://leetcode.com/playground/eMErFX2D/shared" frameBorder="0" width="100%" height="450"></iframe>\n\n**Complexity**\n- Time: `O(N + KlogN)`, where `N <= 10^5` is length of `nums` array, `K <= N`.\n\t- `heapify(maxHeap)` costs `O(N)`\n\t- `heappop(maxHeap)` k times costs `O(KlogN)`\n- Space: `O(N)`\n\n---\n**\u2714\uFE0F Solution 2: Bucket Sort**\n- Since the array `nums` has size of `n`, the frequency can be up to `n`.\n- We can create bucket to store numbers by frequency.\n- Then start `bucketIdx = n`, we can get the `k` numbers which have largest frequency.\n<iframe src="https://leetcode.com/playground/htcSy7mw/shared" frameBorder="0" width="100%" height="460"></iframe>\n\n**Complexity**\n- Time: `O(N)`, where `N <= 10^5` is length of `nums` array.\n- Space: `O(N)`
120
1
['Heap (Priority Queue)', 'Bucket Sort']
6
top-k-frequent-elements
C++ O(nlogk) and O(n) solutions
c-onlogk-and-on-solutions-by-clark3-1hao
Solution 1: Using a min heap. O(nlogk)\n\n class Solution {\n public:\n vector topKFrequent(vector& nums, int k) {\n unordered_map count
clark3
NORMAL
2016-05-02T11:28:18+00:00
2018-10-10T03:53:28.345804+00:00
19,633
false
Solution 1: Using a min heap. O(nlogk)\n\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> counts;\n priority_queue<int, vector<int>, greater<int>> max_k;\n for(auto i : nums) ++counts[i];\n for(auto & i : counts) {\n max_k.push(i.second);\n // Size of the min heap is maintained at equal to or below k\n while(max_k.size() > k) max_k.pop();\n }\n vector<int> res;\n for(auto & i : counts) {\n if(i.second >= max_k.top()) res.push_back(i.first);\n }\n return res;\n }\n };\n\nSoution 2: Bucket sort. O(n)\n\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> counts;\n for(auto i : nums) ++counts[i];\n \n vector<vector<int>> buckets(nums.size() + 1);\n for(auto & k : counts) \n buckets[k.second].push_back(k.first);\n reverse(begin(buckets), end(buckets));\n \n vector<int> res;\n for(auto & bucket: buckets) \n for(auto i : bucket) {\n res.push_back(i);\n if(res.size() == k) return res;\n }\n \n return res;\n }\n };
89
2
[]
8
top-k-frequent-elements
[ Python ] ✅✅ Simple Python Solution Using Dictionary ( HashMap ) ✌👍
python-simple-python-solution-using-dict-l0ou
If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F \n# Runtime: 115 ms, faster than 46.79% of Python3 online submissi
ashok_kumar_meghvanshi
NORMAL
2022-04-09T06:41:07.170858+00:00
2023-09-05T10:21:15.559099+00:00
31,589
false
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F \n# Runtime: 115 ms, faster than 46.79% of Python3 online submissions for Top K Frequent Elements.\n# Memory Usage: 21.1 MB, less than 41.02% of Python3 online submissions for Top K Frequent Elements.\n\n\tclass Solution:\n\t\tdef topKFrequent(self, nums: List[int], k: int) -> List[int]:\n\n\t\t\tfrequency = {}\n\n\t\t\tfor num in nums:\n\n\t\t\t\tif num not in frequency:\n\n\t\t\t\t\tfrequency[num] = 1\n\n\t\t\t\telse:\n\n\t\t\t\t\tfrequency[num] = frequency[num] + 1\n\n\t\t\tfrequency = dict(sorted(frequency.items(), key=lambda x: x[1], reverse=True))\n\n\t\t\tresult = list(frequency.keys())[:k]\n\n\t\t\treturn result\n\t\t\t\n\tTime Complexity : O(n * log(n))\n\tSpace Complexity : O(n)\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D
80
3
['Python', 'Python3']
17
top-k-frequent-elements
Easy & Simple Java Solution for Interviews - Heap + HashMap
easy-simple-java-solution-for-interviews-4z0a
Algorithm Steps:\n1) Create a frequency table\n2) Create a Max Heap and add all the distinct elements\n3) Poll top k frequent elements off the Heap\n\nTime & Sp
doej4566
NORMAL
2019-08-04T02:11:51.937567+00:00
2019-08-04T02:13:31.180169+00:00
15,203
false
**Algorithm Steps:**\n1) Create a frequency table\n2) Create a Max Heap and add all the distinct elements\n3) Poll top k frequent elements off the Heap\n\n**Time & Space Complexity Analysis:**\n\nN = # of elements in the input array\nD = # of distinct (unique) elements in the input array\n\nBuilding the HashMap: O(N) time\n* Add all the N elements into the HashMap and add thier frequency\n\nBuilding the Heap: O(D) time\n* https://www.geeksforgeeks.org/time-complexity-of-building-a-heap/\n* ^Here is a proof that shows that building a heap of N elements will take O(N) time\n* In our case we are building a heap of D elements = O(D) time\n\nPoll K distinct elements from the Heap: O(K log D) time\n* There are D elements in the Heap and we call poll() K times = O(K log D) time\n\n**Total Time Complexity = O(K log D)\nTotal Space Complexity = O(D), this is the size of the heap.**\n```\nclass Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n for(int num : nums){ map.put(num, map.getOrDefault(num, 0) + 1); }\n \n Queue<Integer> heap = new PriorityQueue<>((a, b) -> map.get(b) - map.get(a));\n for(int key : map.keySet()){ heap.add(key); }\n \n List<Integer> ans = new ArrayList<>();\n for(int i = 0; i < k; i++){\n ans.add(heap.poll());\n }\n \n return ans;\n }\n}\n```
80
2
['Heap (Priority Queue)', 'Java']
18
top-k-frequent-elements
[Python] [Explained] Two Simple Heap solutions
python-explained-two-simple-heap-solutio-5x8l
Approach 1\nTime: O(NlogN)\nSpace: O(N)\n\n- Build a frequency dictionary - invert the sign of the frequency (-ve frequency serves as priority key for the heap
Hieroglyphs
NORMAL
2020-01-19T15:58:32.776408+00:00
2020-01-19T15:59:35.087451+00:00
16,629
false
**Approach 1**\n*Time: O(NlogN)*\n*Space: O(N)*\n\n- Build a frequency dictionary - invert the sign of the frequency (-ve frequency serves as priority key for the heap later)\n- Push all (item, -ve freq) pairs into heap\n- Pop k items from heap and append to a result list\n- return list\n\n```\nif not nums:\n\treturn []\n\nif len(nums) == 1:\n\t return nums[0]\n\n# first find freq - freq dict\nd = {}\nfor num in nums:\n\tif num in d:\n\t\td[num] -= 1 # reverse the sign on the freq for the heap\'s sake\n\telse:\n\t\td[num] = -1\n\nh = []\nfrom heapq import heappush, heappop\nfor key in d:\n\theappush(h, (d[key], key))\n\nres = []\ncount = 0\nwhile count < k:\n\tfrq, item = heappop(h)\n\tres.append(item)\n\tcount += 1\nreturn res\n```\n\n**Approach 2**\n*Time: O(Nlogk)*\n*Space: O(N)*\n\n- Build a frequency dictionary (freq is positive)\n- Build a heap\n- Make sure heap conatins k items at maximum by popping out the items with least frequency as you push to heap\n- The time complexity of adding an element in a heap is O(log(k)) and we do it N times that means O(Nlog(k)) time complexity for this step.\n- Heap now contains k items (the desired output basically)\n- Pop and append to the output list - O(klog(k))\n- return list\n\n```\nif len(nums) == 1:\n return [nums[0]]\n\n# freq dict\nd = {}\nfor num in nums:\n\tif num in d:\n\t\td[num] += 1\n\telse:\n\t\td[num] = 1\n\n# insert k items into heap O(nlog(k))\nh = []\nfrom heapq import heappush, heappop\nfor key in d: # O(N)\n\theappush(h, (d[key], key)) # freq, item - O(log(k))\n\tif len(h) > k:\n\t\theappop(h)\n\nres = []\nwhile h: # O(k)\n\tfrq, item = heappop(h) # O(logk)\n\tres.append(item)\nreturn res\n```
69
1
['Heap (Priority Queue)', 'Python']
6
top-k-frequent-elements
[Java] O(n) - explained with pictures
java-on-explained-with-pictures-by-nonna-77n3
The main idea is to use Bucket Sort \n1. Create Frequency map:\n 1.1 Iterate thru the given nums[] array \n 1.2. With each iteration - check if map alread
NonnaD
NORMAL
2022-01-05T04:41:25.358022+00:00
2022-03-23T00:14:37.691968+00:00
7,122
false
The main idea is to use Bucket Sort \n1. Create Frequency map:\n 1.1 Iterate thru the given nums[] array \n 1.2. With each iteration - check if map already contains current key\n If current key is already in the map just increase the value for this key\n Else add key value pair. \n Where key is current int and value is 1 (1 -> we encounter given key for the first time)\n2. Create List<Integer>[] freqSorted\n index of freqSorted[] arr will represent the value from our map \n Why not use int[] arr? Multiple values can have the same frequency that\'s why we use List<Integer>[] array of lists instead of regular array \n Iterate thrue the map and for each value add key at the index of that value \n3. If we look at freqSorted arr we can see that most frequent elements are located at the end of arr \n and leat frequent elemnts at the begining \n Last step is to iterate from the end to the begining of the arr and add elements to result List\n![image](https://assets.leetcode.com/users/images/dfb6e015-851c-4dab-8629-789a84e5eb88_1641357628.0177674.png)\n```\npublic int[] topKFrequent(int[] nums, int k) {\n\t//create array of lists to be used as buckets\n\t//we need to sort by frequency \n\t//NOTE: if we know frequencies are unique we can use simple int[]\n\t//but since we can have duplicated frequencies we need a way to store all duplicates \n\t//thats why we use List<Integer>[] instead of simple int[]\n\tList<Integer>[] freqSorted = new List[nums.length +1];\n\tMap<Integer, Integer> frequencyMap = new HashMap();\n\tList<Integer> res = new ArrayList();\n\n\t//find how often each char occured\n\tfor(int n: nums)\n\t\tfrequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);\n\n //iterate thru frequency map and add to freqSorted key at position frequency\n //NOTE: each index of freqSorted represents frequency \n //Example: at position freqSorted[3] we will store all elements that appeared 3 times\n for(int key: frequencyMap.keySet()){\n\t if(freqSorted[frequencyMap.get(key)] == null)\n\t\t freqSorted[frequencyMap.get(key)] = new ArrayList();\n\t freqSorted[frequencyMap.get(key)].add(key);\n }\n\n //iterate again starting from right to left \n //since we need most frequent \n //NOTE: if problem asks for least frequent nums iterate from left to right \n for(int i = freqSorted.length - 1; i >= 0 && res.size() < k; i--)\n\t if(freqSorted[i] != null){\n\t\t\tres.addAll(freqSorted[i]);\n }\n\n return res.stream().mapToInt(i->i).toArray();\n}}\n```
67
0
['Java']
7
top-k-frequent-elements
C++ Two Short Solutions, O(nlogn) - Map+Queue / O(n) - Bucket Sort
c-two-short-solutions-onlogn-mapqueue-on-0hbh
Map + Priority Queue - O(nlogn)\n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> freq;\n
yehudisk
NORMAL
2021-07-14T07:54:14.799892+00:00
2021-07-14T08:22:07.510331+00:00
5,178
false
**Map + Priority Queue - O(nlogn)**\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> freq;\n for (auto num : nums) freq[num]++;\n \n priority_queue<pair<int, int>> pq;\n for (auto [a, b] : freq) pq.push({b, a});\n \n vector<int> res;\n while (k) {\n res.push_back(pq.top().second);\n pq.pop();\n k--;\n }\n \n return res;\n }\n};\n```\n****\n**Bucket Sort - O(n)**\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> freq;\n for (auto num : nums) freq[num]++;\n \n vector<vector<int>> buckets(nums.size()+1);\n for (auto [a, b] : freq)\n buckets[b].push_back(a);\n \n vector<int> res;\n for (int i = nums.size(); k; i--) {\n for (auto a : buckets[i]) {\n res.push_back(a);\n k--;\n }\n }\n \n return res;\n }\n};\n```\n**Like it? please upvote!**
65
2
['C']
5
top-k-frequent-elements
Python | 4 Ways of doing same simple thing
python-4-ways-of-doing-same-simple-thing-rzzn
Method 1: Using Counter + most_common()\nInternally most_common() method is implemented by constructing a heap and using nlargest() function from the heapq libr
ancoderr
NORMAL
2022-01-20T19:50:38.603792+00:00
2022-01-20T19:50:38.603853+00:00
15,272
false
#### Method 1: Using Counter + most_common()\nInternally most_common() method is implemented by constructing a heap and using nlargest() function from the heapq library as done in **Methon 2**\n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n freq_table = Counter(nums)\n ans_table = freq_table.most_common()\n ans = []\n for key, _ in ans_table:\n if k <= 0:\n break\n k -= 1\n ans.append(key)\n return ans\n```\n#### Method 2: Using Counter + Heap + nlargest\n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n freq_table = Counter(nums)\n heap = []\n for i in freq_table.keys():\n heappush(heap, (freq_table[i], i))\n freq_table = nlargest(k,heap)\n ans = []\n for i, j in freq_table:\n ans.append(j)\n return ans\n```\n#### Method 3: Using Counter + Selecting Manually:\nHere we have pushed `-freq_table[i]` to replicate max heap behaviour. Then I have simply done k pops to get k most frequent values.\n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n freq_table = Counter(nums)\n heap = []\n for i in freq_table.keys():\n heappush(heap, (-freq_table[i], i))\n ans = []\n while k > 0:\n k -= 1\n ans.append(heappop(heap)[1])\n return ans\n\n\n```\n#### Method 4: Done Manually Entirely\n**Recommended for an interview situation.** During an interview using tons of library functions is generally not advisable. Especially when these things be replicated with relative ease without drastically increasing the size of your code or its complexity. However you can always ask the interviewer if you can use Library Functions as they might just want to see your apporach to the problem rather than your programming skills.\n\n**NOTE:** *heapq.heappushpop* allows us to add element to the heap without changing its size. It basically does a push first then pop. So it is used in situations where you want to add values into the heap but dont want to change its size. This keeps the size fixed but keeps removing the min or max(as you may have used it) there by finally containing only largest or smallests of the added values. \n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n freq_table = {}\n for i in nums:\n freq_table[i] = freq_table.get(i, 0) + 1\n heap = []\n for i in freq_table.keys():\n if len(heap) == k: # If size is k then we dont want to increase the size further \n heappushpop(heap, (freq_table[i], i))\n else: # Size is not k then freely push values\n heappush(heap, (freq_table[i], i))\n\t\t# After this operation the heap contains only k largest values of all the values in nums\n ans = []\n while k > 0:\n k -= 1\n ans.append(heappop(heap)[1])\n return ans\n```\nGive an \u2B06\uFE0Fupvote if you found this article helpful. Happy Coding!
61
0
['Heap (Priority Queue)', 'Python', 'Python3']
8
top-k-frequent-elements
1-line Python Solution using Counter with explanation
1-line-python-solution-using-counter-wit-c7tv
import collections\n \n class Solution(object):\n def topKFrequent(self, nums, k):\n """\n :type nums: List[int]\n
myliu
NORMAL
2016-05-03T00:48:08+00:00
2018-09-16T01:25:27.020184+00:00
26,606
false
import collections\n \n class Solution(object):\n def topKFrequent(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n """\n # Use Counter to extract the top k frequent elements\n # most_common(k) return a list of tuples, where the first item of the tuple is the element,\n # and the second item of the tuple is the count\n # Thus, the built-in zip function could be used to extract the first item from the tuples\n return zip(*collections.Counter(nums).most_common(k))[0]
60
17
['Python']
24
top-k-frequent-elements
👏Beats 96.39% of users with Java🎉||✅Simple & Well Explained Bucket Sorting HashMap Solution🔥💥
beats-9639-of-users-with-javasimple-well-sl49
Intuition\nCreate hashmap and store every element with frequency, after that we create bucket and add elements that is having bucket\'s index frequency.\nIterat
Rutvik_Jasani
NORMAL
2024-04-16T14:14:24.682901+00:00
2024-04-18T10:08:20.206258+00:00
14,369
false
# Intuition\nCreate hashmap and store every element with frequency, after that we create bucket and add elements that is having bucket\'s index frequency.\nIterate bucket from last to first and add last k elements into the ans and return ans.\n\n# I Think This Can Help You(For Proof Click on the Image)\n[![Screenshot 2024-02-24 232407.png](https://assets.leetcode.com/users/images/3a0b5e26-b794-4a1d-8ce9-0786f4f41a96_1713276551.4992468.png)](https://leetcode.com/problems/top-k-frequent-elements/submissions/1234000884/)\n\n# Approach\n1. **Initialize Data Structures**:\n ```java\n List<Integer>[] bucket = new List[nums.length + 1];\n HashMap<Integer, Integer> hm = new HashMap<>();\n ```\n - `bucket`: This array of lists will store elements based on their frequency. The index represents the frequency, and the list at each index contains elements with that frequency.\n - `hm`: This HashMap will store the frequency of each element in the `nums` array.\n2. **Count Frequencies**:\n ```java\n for (int num : nums) {\n hm.put(num, hm.getOrDefault(num, 0) + 1);\n }\n ```\n - Loop through the `nums` array and count the frequency of each element using the HashMap `hm`.\n3. **Bucketing Elements**:\n ```java\n for (int key : hm.keySet()) {\n int freq = hm.get(key);\n if (bucket[freq] == null) {\n bucket[freq] = new ArrayList<>();\n }\n bucket[freq].add(key);\n }\n ```\n - Iterate through the keys of the HashMap `hm`.\n - For each key, get its frequency from `hm`.\n - Add the key to the corresponding bucket based on its frequency.\n4. **Extract Top K Frequent Elements**:\n ```java\n int[] ans = new int[k];\n int pos = 0;\n for (int i = bucket.length - 1; i >= 0; i--) {\n if (bucket[i] != null) {\n for (int j = 0; j < bucket[i].size() && pos < k; j++) {\n ans[pos] = bucket[i].get(j);\n pos++;\n }\n }\n }\n ```\n - Initialize the `ans` array to store the top k frequent elements.\n - Iterate over the `bucket` array in reverse order (from higher frequencies to lower frequencies).\n - For each bucket that is not null, iterate through its elements.\n - Add the elements to the `ans` array until it\'s filled with k elements or until there are no more elements left in the buckets.\n5. **Return the Result**:\n ```java\n return ans;\n ```\n - Return the `ans` array containing the top k frequent elements.\n\n# Complexity\n- Time complexity:\nO(n) --> bucket storing only nums values.\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n List<Integer>[] bucket = new List[nums.length + 1];\n HashMap<Integer, Integer> hm = new HashMap<>();\n for (int num : nums) {\n hm.put(num, hm.getOrDefault(num,0) + 1);\n }\n for (int key : hm.keySet()) {\n int freq = hm.get(key);\n if (bucket[freq] == null) {\n bucket[freq] = new ArrayList<>();\n }\n bucket[freq].add(key);\n }\n int[] ans = new int[k];\n int pos = 0;\n for (int i = bucket.length - 1; i >= 0; i--) {\n if (bucket[i] != null) {\n for (int j = 0; j < bucket[i].size() && pos < k; j++) {\n ans[pos] = bucket[i].get(j);\n pos++;\n }\n }\n }\n return ans;\n }\n}\n```\n\n![_88a70899-aa2e-436d-8727-f561b4e9f641.jpeg](https://assets.leetcode.com/users/images/0d234192-eee8-4592-9285-facba48f5c8e_1713276656.4913945.jpeg)\n
59
1
['Array', 'Hash Table', 'Divide and Conquer', 'Sorting', 'Heap (Priority Queue)', 'Bucket Sort', 'Counting', 'Quickselect', 'Java']
6
top-k-frequent-elements
[C/C++] Short and simple o(n) time. No need to burn nlogn time on the sort.
cc-short-and-simple-on-time-no-need-to-b-r85w
The top k elements do not need to be in asending order, which allows for a partial sort. c++ has std::nth_element for just such an occasion. A simple hashmap to
christrompf
NORMAL
2018-07-09T13:10:00.856621+00:00
2023-05-22T13:31:10.910304+00:00
11,282
false
The top k elements do not need to be in asending order, which allows for a partial sort. c++ has `std::nth_element` for just such an occasion. A simple hashmap to count the frequency is the only other thing needed.\n\n# C++\n\n### Using stl for the win.\n```cpp\n vector<int> topKFrequent(vector<int>& nums, int k) {\n std::unordered_map<int, int> freq;\n std::vector<int> ret;\n ret.reserve(nums.size());\n for (auto n : nums) {\n if (1 == ++freq[n]) {\n // Count the frequency for each int, storing each new int as we go\n ret.push_back(n);\n }\n }\n\n // Piviot around the kth element using custom compare. Elements are not sorted, just\n // reordered such that all elements in the range [0, k] are greater than those in [k + 1, n)\n // This is an (average) O(n) operation\n std::nth_element(ret.begin(), ret.begin() + k - 1, ret.end(), [&freq] (int l, int r) -> bool {\n return freq[l] > freq[r];\n });\n ret.resize(k);\n return ret;\n }\n```\n\n### Using my own recursive implementation of a quick select.\n```cpp\n vector<int> topKFrequent(vector<int>& nums, int k) {\n std::unordered_map<int, int> freq;\n std::vector<int> ret;\n for (auto n : nums) {\n // Count the frequency for each int, storing each new int as we go\n if (1 == ++freq[n]) {\n ret.push_back(n);\n }\n }\n\n std::function <void (int lo, int hi)> quick_select;\n quick_select = [&freq, &ret, k, &quick_select] (int lo, int hi) -> void {\n int pivot_freq = freq[ret[hi - 1]];\n int idx = lo;\n // Move all elements that have a greater frequency than our pivot to be at the front \n for (int i = lo; i < hi; ++i) {\n if (freq[ret[i]] >= pivot_freq) {\n swap(ret[i], ret[idx++]);\n }\n }\n if (idx == k - 1) {\n return;\n } else if (idx < k - 1) {\n // Not enough elements selected\n return quick_select(idx, hi);\n } else {\n // Too many elements selected\n return quick_select(lo, idx - 1);\n }\n };\n\n quick_select(0, ret.size());\n ret.resize(k);\n return ret;\n }\n```\n\n### Using my own iterative implementation of a quick select.\n```cpp\nvector<int> topKFrequent(vector<int>& nums, int k) {\n std::unordered_map<int, int> freq;\n std::vector<int> ret;\n ret.reserve(nums.size());\n for (auto n : nums) {\n if (1 == ++freq[n]) {\n // Count the frequency for each int, storing each new int as we go\n ret.push_back(n);\n }\n }\n\n // Find the top k most frequent using O(n) time, O(1) space quick select \n int lo = 0;\n int hi = ret.size();\n int idx = lo;\n for (;;) {\n int pivot_freq = freq[ret[hi - 1]];\n for (int i = lo; i < hi; ++i) {\n if (freq[ret[i]] >= pivot_freq) {\n swap(ret[i], ret[idx++]);\n }\n }\n\n if (idx == k - 1) {\n break;\n } else if (idx < k - 1) {\n // Not enough elements selected\n lo = idx;\n } else if (idx > k - 1) {\n // Too many elements selected\n hi = idx - 1;\n idx = lo;\n }\n }\n\n ret.resize(k);\n return ret;\n}\n```\n\n# C\nSimilar to the c++ solution, except the hash tables takes more work because I use uthash since c doesn\'t have an inbuild hashtable.\n\nI redid the quickselect to use a three way partition instead of a two way partion. The three way partition is more forgiving when there are duplicate entries to be partitioned.\n\n```c\nstruct freq_hash {\n int value;\n int count;\n UT_hash_handle hh;\n};\n\nstatic\nint get_freq(struct freq_hash* table, int val) {\n struct freq_hash* entry;\n HASH_FIND_INT(table, &val, entry);\n return entry->count;\n}\n\nint* topKFrequent(int* nums, int numsSize, int k, int* returnSize){\n struct freq_hash* table = NULL;\n int* const ret = malloc(numsSize * sizeof(*ret));\n int* pos = ret;\n *returnSize = k;\n\n // Count the frequencies of each number while storing the unique values in the return array\n struct freq_hash entries[numsSize];\n struct freq_hash* entries_pos = entries;\n for (int i = 0; i < numsSize; ++i) {\n struct freq_hash* entry;\n HASH_FIND_INT(table, &nums[i], entry);\n if (!entry) {\n entry = entries_pos++;\n entry->value = nums[i];\n entry->count = 1;\n *pos++ = nums[i];\n HASH_ADD_INT(table, value, entry);\n } else {\n ++entry->count;\n }\n }\n\n int sz = pos - ret;\n int lo = 0;\n int hi = sz;\n for (;;) {\n // Parition around the frequency such that;\n // [lo, above_end) Will be the range that is greater than the pivot frequency\n // [above_end, equal_end) Will be the range that is equal to the pivot frequency\n // [equal_end, hi) Will be the range that is less than the pivot frequency\n int pivot = lo + (hi - lo) / 2;\n int pivot_freq = get_freq(table, ret[pivot]);\n int above_end = lo;\n int equal_end = lo;\n int below_start = hi;\n while (equal_end < below_start) {\n int val = ret[equal_end];\n int freq = get_freq(table, val);\n if (pivot_freq < freq) {\n // Move to the greater than pivot pile\n ret[equal_end++] = ret[above_end];\n ret[above_end++] = val;\n } else if (pivot_freq > freq) {\n // Move to the less than pivot pile\n ret[equal_end] = ret[--below_start];\n ret[below_start] = val;\n } else {\n // Increase the width of the equal pile\n ++equal_end;\n }\n }\n\n if (equal_end < k) {\n // Not enough elements selected, increase the range to increase the count\n lo = equal_end;\n } else if (above_end > k) {\n // Too many elements selected, reduce the range to reduce the count\n hi = above_end;\n } else {\n // k falls in the range [above_end, equal_end) and se we\'re done\n break;\n }\n }\n\n HASH_CLEAR(hh, table);\n return realloc(ret, k * sizeof(*ret));\n}\n```
53
2
['C', 'C++']
9
top-k-frequent-elements
Beats 100% of users with C++ || Using Vector || Using Map || Using Pair || Step By Step Explain ||
beats-100-of-users-with-c-using-vector-u-z9ku
Abhiraj pratap Singh\n\n---\n\n# if you like the solution please UPVOTE it....\n\n---\n\n# Intuition\n Describe your first thoughts on how to solve this problem
abhirajpratapsingh
NORMAL
2024-02-27T12:08:44.905590+00:00
2024-02-27T12:08:44.905623+00:00
7,751
false
# Abhiraj pratap Singh\n\n---\n\n# if you like the solution please UPVOTE it....\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The problem requires finding the top K frequent elements in an array of integers. One approach is to use a map to count the frequency of each element, then sort the elements based on their frequency and return the top K elements.\n\n---\n\n![Screenshot (47).png](https://assets.leetcode.com/users/images/c9793753-b787-44f2-9ddb-546ce4d37845_1709034936.8200002.png)\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize an empty map mp to store the frequency of each element.\n- Iterate through the input nums array and update the frequency of each element in the map.\n- Create a vector of pairs v, where each pair consists of the frequency and the corresponding element.\n- Sort the vector v in descending order based on the frequency.\n- Iterate through the sorted vector v and insert the elements into the result vector ans until k elements are inserted.\n- Return the result vector ans.\n\n---\n\n\n# Complexity\n\n- **Time complexity :**\n - Constructing the frequency map: O(n)\n - Sorting the vector of pairs: O(n log n)\n - Extracting the top K elements: O(k)\n - Overall, the **time complexity is O(n log n),** where n is the size of the input array nums.\n- **Space complexity :**\n - Additional space used for the map and the vector of pairs: O(n)\n - Space required for the result vector: O(k)\nOverall, the space complexity is **O(n).**\n\n---\n\n# Code\n```\n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) \n {\n vector<int>ans;\n map<int,int>mp;\n for(int i=0;i<nums.size();i++)\n mp[nums[i]]++;\n vector<pair<int,int>>v;\n for(auto it : mp )\n v.push_back(make_pair(it.second,it.first));\n sort(v.rbegin(),v.rend());\n for(int i=0;i<v.size() && k!=0 ;i++)\n {\n ans.push_back(v[i].second);\n k--;\n } \n return ans; \n }\n};\n```\n\n---\n# if you like the solution please UPVOTE it.....\n\n---\n\n\n![discord-discordgifemoji.gif](https://assets.leetcode.com/users/images/e25c40a2-086e-4ffb-b92b-2256fe908675_1709035656.1010334.gif)\n\n![fucking-die-redditor-stupid-cuck-funny-cat.gif](https://assets.leetcode.com/users/images/bd302de8-738a-4f3f-a049-cc75910c25aa_1709035661.155453.gif)\n\n---\n---\n
52
1
['Array', 'Hash Table', 'Divide and Conquer', 'Sorting', 'Heap (Priority Queue)', 'Bucket Sort', 'Counting', 'Quickselect', 'C++']
4
top-k-frequent-elements
[Regards] Summary Of 3 Concise C++ Implementations
regards-summary-of-3-concise-c-implement-nt7r
This problem's C++ solutions rely heavily on different data structure design.\n\n First let us check the max-heap (priority_queue) based solutions\n\n class
rainbowsecret
NORMAL
2016-05-09T12:34:12+00:00
2016-05-09T12:34:12+00:00
9,094
false
This problem's C++ solutions rely heavily on different data structure design.\n\n First let us check the max-heap (priority_queue) based solutions\n\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int> map;\n for(int num : nums){\n map[num]++;\n }\n \n vector<int> res;\n /** use the priority queue, like the max-heap , we will keep (size-k) smallest elements in the queue**/\n /** pair<first, second>: first is frequency, second is number **/\n priority_queue<pair<int,int>> pq; \n for(auto it = map.begin(); it != map.end(); it++){\n pq.push(make_pair(it->second, it->first));\n /** onece the size bigger than size-k, we will pop the value, which is the top k frequent element value **/\n if(pq.size() > (int)map.size() - k){\n res.push_back(pq.top().second);\n pq.pop();\n }\n }\n return res;\n }\n };\n\n Now let us check the frequency-based array method solutions\n\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> m;\n for (int num : nums)\n ++m[num];\n /** as the word frequencies is at most nums.size() **/\n vector<vector<int>> buckets(nums.size() + 1);\n for (auto p : m) \n buckets[p.second].push_back(p.first);\n /** we can fetch the top k largest element value from the array **/ \n vector<int> ans;\n for (int i = buckets.size() - 1; i >= 0 && ans.size() < k; --i)\n {\n for (int num : buckets[i])\n {\n ans.push_back(num);\n if (ans.size() == k)\n break;\n }\n }\n return ans;\n }\n };\n\nThe third solution is based on the C++ API : nth_element() to resort the array to left half and right half.\n\n\n\n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> counts;\n for (const auto& i : nums) \n {\n ++ counts[i];\n }\n /** pair : (-frequency, key) **/\n vector<pair<int, int>> p;\n for (auto it = counts.begin(); it != counts.end(); ++ it) \n {\n p.emplace_back(-(it->second), it->first);\n }\n /** nth_element() call will put the (k-1)-th element on its position,\n * the left (k-1) element is smaller than the key, the right bigger **/\n nth_element(p.begin(), p.begin() + k - 1, p.end());\n vector<int> result;\n for (int i = 0; i < k; i++) \n {\n result.emplace_back(p[i].second);\n }\n return result;\n }\n };
49
0
['C++']
6
top-k-frequent-elements
[Python3] BucketSort + Heap (2 lines) || beats 94%
python3-bucketsort-heap-2-lines-beats-94-6dz4
BucketSort:\n\n1. Count frequency for all numbers using Counter (or manually).\n2. Create buckets for grouping items by frequency. Buckets count is equal to num
yourick
NORMAL
2023-05-22T00:38:08.741997+00:00
2024-02-29T10:49:22.777747+00:00
14,831
false
### BucketSort:\n\n1. Count frequency for all numbers using Counter (or manually).\n2. Create buckets for grouping items by frequency. Buckets count is equal to number of nums. For example: ```nums[1,1,1,1,2,2,3,4] => buckets = [0:[], 1:[3,4], 2:[2], 3:[], 4:[1]]```. Instead of an array, you can use a dictionary for buckets, as some buckets may be empty.\n3. Group numbers by relevant bucket (according frequency).\n4. Now all values in buckets sorted by frequency in ascending order. Just return k most frequent values from the end.\n\n\n```python3 []\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n cnt = Counter(nums)\n buckets = [[] for _ in range(len(nums) + 1)]\n for val, freq in cnt.items():\n buckets[freq].append(val)\n \n return list(chain(*buckets[::-1]))[:k]\n```\n###### Insted of one line code `return list(chain(*buckets[::-1]))[:k]` you can do calculation manually:\n```python3 []\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n cnt = Counter(nums)\n buckets = [[] for _ in range(len(nums) + 1)]\n for val, freq in cnt.items():\n buckets[freq].append(val)\n \n res = []\n for bucket in reversed(buckets):\n for val in bucket:\n res.append(val)\n k -=1\n if k == 0:\n return res\n```\n\n---\n\n\n### Heap via Counter:\n###### Counter.most_common method is just a shell over heapq.nlargest, see the [code](https://github.com/python/cpython/blob/1b85f4ec45a5d63188ee3866bd55eb29fdec7fbf/Lib/collections/__init__.py#L575)\n\n```python3 []\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n cnt = Counter(nums)\n return [val for val, _ in cnt.most_common(k)]\n```\n![Screenshot 2023-07-23 at 20.30.45.png](https://assets.leetcode.com/users/images/cc864c7b-00f5-421e-aef0-689eeebcc63c_1690133481.8235292.png)\n
47
0
['Heap (Priority Queue)', 'Bucket Sort', 'Counting', 'Python', 'Python3']
2
top-k-frequent-elements
C++ | Easy Approach | UNORDERED_MAP | PRIORITY_QUEUE
c-easy-approach-unordered_map-priority_q-jndy
Intuition\nAs the question says to get top k frequent elements, we are using priority queue to solve this question.\n\nHint\nTop K type questions can be solved
deepak1408
NORMAL
2023-03-19T12:11:54.631568+00:00
2023-03-26T05:49:57.285577+00:00
6,523
false
# Intuition\nAs the question says to get top k frequent elements, we are using priority queue to solve this question.\n\n**Hint**\nTop K type questions can be solved using prority queue in an efficient way.\n\n# Approach\nFirst let us store the frequency of each element in the map. Let us create a priority queue of a pair (MaxHeap) in which first element is frquency of the number in the array and second element is the number. The priority queue sorts the pairs in decreasing order of their frequencies. Now store the top k elements in the answer vector and return it.\n\nLet us see the time complexity of the approach.\n\nAverage case for unordered map insertion takes O(N) for inserting all the elements.\nAverage case for priority queue insertion takes O(NlogN) for inserting all the elements.\nAverage case to access top k elements takes O(K)\n\nOverall time is O(N+NlogN+K) = O(NlogN)\n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n priority_queue<pair<int,int>>pq;\n unordered_map<int,int>mpp;\n for(auto i:nums){\n mpp[i]++;\n }\n for(auto i:mpp){\n pq.push({i.second,i.first});\n }\n vector<int>ans;\n while(k-- && !pq.empty()){\n ans.push_back(pq.top().second);\n pq.pop();\n }\n return ans;\n }\n};\n```
47
0
['Hash Table', 'Heap (Priority Queue)', 'C++']
2
top-k-frequent-elements
*Java* straightforward O(N + (N-k)lg k) solution
java-straightforward-on-n-klg-k-solution-8gqg
Idea is very straightforward:\n\n - build a counter map that maps a num to its frequency\n - build a heap/priority queue that keeps track of k most significant
elementnotfoundexception
NORMAL
2016-05-02T20:36:28+00:00
2016-05-02T20:36:28+00:00
18,348
false
Idea is very straightforward:\n\n - build a counter map that maps a num to its frequency\n - build a heap/priority queue that keeps track of `k` most significant entries\n - iterate through the final heap and get the keys\n\nCode in Java:\n\n public List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> counterMap = new HashMap<>();\n for(int num : nums) {\n int count = counterMap.getOrDefault(num, 0);\n counterMap.put(num, count+1);\n }\n \n PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((a, b) -> a.getValue()-b.getValue());\n for(Map.Entry<Integer, Integer> entry : counterMap.entrySet()) {\n pq.offer(entry);\n if(pq.size() > k) pq.poll();\n }\n \n List<Integer> res = new LinkedList<>();\n while(!pq.isEmpty()) {\n res.add(0, pq.poll().getKey());\n }\n return res;\n }
45
1
[]
13
top-k-frequent-elements
✅ 3 Best Swift Solutions | Easy To Understand
3-best-swift-solutions-easy-to-understan-g34e
First solution using Dictionary\n\n## Approach\nThis approach to solving the problem involves using a dictionary to count the frequency of each element in the i
smthinthewayy
NORMAL
2023-04-17T08:16:13.856955+00:00
2023-04-17T10:31:35.365276+00:00
2,381
false
# First solution using Dictionary\n\n## Approach\nThis approach to solving the problem involves using a dictionary to count the *frequency* of each element in the input array, and then sorting the dictionary by value in *descending* order to obtain the top `k` *frequent* elements.\n\nThe function first creates an empty dictionary `frequencyDict` to store the frequency of each element in the input array. It then iterates over the input array, using the `default` parameter of the subscript operator to increment the value in the dictionary for each encountered element. This ensures that the dictionary always contains a value for each element, even if it hasn\'t been encountered yet.\n\nNext, the function sorts the dictionary by value in descending order using the `sorted` function, which returns an array of key-value pairs. The sort closure is defined as `$0.value > $1.value`, which compares the values of each key-value pair and returns `true` if the first value is greater than the second. This ensures that the dictionary is sorted in *descending* order of frequency.\n\nFinally, the function creates a result array `result` and appends the keys of the first `k` elements in the sorted dictionary to it using a for loop. It then returns the resulting array of top `k` *frequent* elements.\n\n## Complexity\nThe *time complexity* of this approach is $$O(n \\cdot \\log n)$$ due to the sorting operation, where $$n$$ is the length of the input array.\n\nThe *space complexity* is also $$O(n)$$, where $$n$$ is the length of the input array, due to the use of a dictionary to store the *frequency* of each element.\n\n## Code\n\n```swift\nclass Solution {\n func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {\n var frequencyDict = [Int: Int]()\n for num in nums {\n frequencyDict[num, default: 0] += 1\n }\n let sortedDict = frequencyDict.sorted { $0.value > $1.value }\n var result = [Int]()\n for i in 0 ..< k {\n result.append(sortedDict[i].key)\n }\n return result\n }\n}\n```\n\n\n---\n\n# Second solution higher-order functions\n\n## Approach\nThis approach to solving the problem uses *higher-order functions* to create a *frequency* dictionary and sort its keys by value in descending order.\n\nThe function first uses the `reduce` function to create a *frequency* dictionary `dict` from the input array. The `reduce` function takes an initial value of an empty dictionary and a closure that updates the dictionary for each element in the input array. The into parameter allows us to specify the initial value as a dictionary, and the closure increments the value corresponding to the current element in the dictionary.\n\nNext, the function chains together several higher-order functions to sort the keys of the dictionary by value in descending order and return the top `k` keys. The keys are sorted using the `sorted` function with a closure that compares the values of each key-value pair. The resulting array of keys is then sliced using the half-open range operator to take the first `k` elements. Finally, the resulting array is converted to a standard array using the `Array` initializer.\n\n\n## Complexity\nThis approach has a *time complexity* of $$O(n \\cdot \\log n)$$ due to the sorting operation, where $$n$$ is the length of the input array.\n\nThe *space complexity* of this approach is $$O(n)$$, where $$n$$ is the length of the input array.\n\n## Code\n\n```swift\nclass Solution {\n func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {\n let dict = nums.reduce(into: [:]) { counts, num in counts[num, default: 0] += 1 }\n return Array(dict.keys.sorted { dict[$0]! > dict[$1]! }[..<k])\n }\n}\n```\n\n\n---\n\n# Third solution using Bucket Sort \n\n## Approach\nIn the given solution, we first create a *frequency* map `freqMap` by iterating through the array `nums`. We use the `default` parameter of the dictionary\'s subscript to set the default value of an element to `0` if it doesn\'t exist in the dictionary. We then increment the *frequency* count of the element in the dictionary.\n\nNext, we create an array of buckets `buckets` of size `nums.count + 1`. We iterate through the `freqMap` to group the elements by their *frequency* in the buckets. Each bucket at index `i` contains all the elements that have a *frequency* of `i`.\n\nFinally, we iterate through the buckets array in reverse order and add the elements to the `result` array until its size becomes equal to `k`. We break out of the loop once we have added `k` elements to the result array.\n\n## Complexity\nThis approach has a *time complexity* of $$O(n)$$, where $$n$$ is the size of the input array `nums`.\n\nThe *space complexity* of this solution is $$O(n)$$, where $$n$$ is the length of the input `nums`.\n\n## Code\n\n```swift\nclass Solution {\n func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {\n var freqMap = [Int: Int]()\n\n for num in nums {\n freqMap[num, default: 0] += 1\n }\n \n var buckets = Array(repeating: [Int](), count: nums.count + 1)\n for (num, freq) in freqMap {\n buckets[freq].append(num)\n }\n \n var result = [Int]()\n for i in (0 ..< buckets.count).reversed() {\n result += buckets[i]\n if result.count == k {\n break\n }\n }\n \n return result\n }\n}\n```\n\n# Upvote ^^\n\n![upvote.png](https://assets.leetcode.com/users/images/b7576286-83bb-41d0-b1ee-9c6d81ad1416_1681719293.9699037.png)\n
39
0
['Array', 'Hash Table', 'Swift', 'Sorting', 'Bucket Sort']
6
top-k-frequent-elements
5.2 (Approach 2) | O(n)✅ | Python & C++(Step by step explanation)✅
52-approach-2-on-python-cstep-by-step-ex-as87
Intuition\n Describe your first thoughts on how to solve this problem. \nMy initial thoughts are to efficiently determine the top k frequent elements in the giv
monster0Freason
NORMAL
2024-01-17T17:08:26.860831+00:00
2024-01-17T17:08:26.860861+00:00
11,713
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy initial thoughts are to efficiently determine the top k frequent elements in the given array. To achieve this, using a bucket sorting approach based on the frequency of elements seems promising.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Create a dictionary (`mp`) to store the frequency of each element in the array:**\n - This step involves iterating through the given array and counting the occurrences of each element using a dictionary. The keys of the dictionary represent the elements, and the values represent their frequencies.\n\n2. **Create buckets to store elements based on their frequency:**\n - Buckets are used to group elements with the same frequency. In this case, we create a list of buckets, where the index of each bucket represents the frequency, and the bucket contains elements with that frequency.\n\n3. **Iterate through the array to populate the `mp` dictionary:**\n - For each element in the array, update the corresponding frequency in the `mp` dictionary.\n\n4. **Iterate through the items in `mp` and distribute elements into the corresponding buckets based on their frequency:**\n - After counting the frequencies in the `mp` dictionary, iterate through its items and distribute elements into the buckets based on their frequencies. Each element goes into the bucket corresponding to its frequency.\n\n5. **Iterate through the buckets from right to left (highest to lowest frequency) and append elements to the answer list until the desired k elements are collected:**\n - Starting from the highest frequency bucket, iterate through the buckets in descending order. For each bucket, append its elements to the answer list until we collect the top k frequent elements.\n\n6. **Return the answer list:**\n - The final step is to return the answer list containing the top k frequent elements.\n\n## Example\nConsider the input array: [1, 1, 1, 2, 2, 3], and k = 2.\n\n- After creating the `mp` dictionary: {1: 3, 2: 2, 3: 1}\n- Buckets: [[], [3], [2], [1]]\n- Iterate through the buckets (from right to left):\n - Bucket with frequency 3: Append 1 to the answer list (top k = 1).\n - Bucket with frequency 2: Append 2 to the answer list (top k = 2).\n - The answer list is [2, 1], which represents the top k frequent elements.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n - Calculating the frequency and populating the dictionary: O(n)\n - Distributing elements into buckets: O(n)\n - Building the answer list: O(k) (assuming k is small)\n - Overall time complexity: O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n - Dictionary `mp`: O(n)\n - Buckets: O(n)\n - Answer list: O(k) (assuming k is small)\n - Overall space complexity: O(n)\n\n# Code(Python)\n```python\n# Python Solution\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n # Step 1: Create a dictionary (`mp`) to store the frequency of each element in the array.\n # Step 2: Create buckets to store elements based on their frequency.\n buckets = [[] for i in range(len(nums) + 1)]\n\n # Step 3: Iterate through the array to populate the `mp` dictionary.\n for n in nums:\n mp[n] = 1 + mp.get(n, 0)\n\n # Step 4: Iterate through the items in `mp` and distribute elements into the corresponding buckets based on their frequency.\n for n, c in mp.items():\n buckets[c].append(n)\n\n # Step 5: Iterate through the buckets from right to left (highest to lowest frequency) and append elements to the answer list until the desired k elements are collected.\n ans = []\n for i in range(len(buckets) - 1, 0, -1):\n for n in buckets[i]:\n ans.append(n)\n if len(ans) == k:\n return ans\n``` \n\n# Code(C++)\n```c++\n# C++ Solution\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n int n = nums.size();\n \n unordered_map<int, int> mp;\n \n // Step 1: Iterate through the vector to populate the `mp` dictionary.\n for (int i = 0; i < n; i++) {\n mp[nums[i]]++;\n }\n \n vector<vector<int>> containers(n + 1);\n \n // Step 2: Iterate through the `mp` dictionary and distribute elements into the corresponding buckets based on their frequency.\n for (auto it = mp.begin(); it != mp.end(); it++) {\n containers[it->second].push_back(it->first);\n }\n \n vector<int> ans;\n \n // Step 3: Iterate through the buckets from right to left (highest to lowest frequency) and append elements to the answer list until the desired k elements are collected.\n for (int i = n; i >= 0; i--) {\n if (ans.size() >= k) {\n break;\n }\n if (!containers[i].empty()) {\n ans.insert(ans.end(), containers[i].begin(), containers[i].end());\n }\n }\n \n return ans;\n }\n};\n``` \n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/0161dd3b-ad9f-4cf6-8c43-49c2e670cc21_1699210823.334661.jpeg)\n
37
0
['C++', 'Python3']
5
top-k-frequent-elements
Easy to Understand Solution [MaxHeap](^///^)
easy-to-understand-solution-maxheap-by-h-anq6
Using MaxHeap\n\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n for(int i :
hi-ravi
NORMAL
2022-04-09T04:02:44.443255+00:00
2022-04-09T13:58:17.313128+00:00
3,861
false
### Using MaxHeap\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n for(int i : nums){ map.put(i, map.getOrDefault(i, 0) + 1); }\n \n Queue<Integer> maxmaxheap = new PriorityQueue<>((a, b) -> map.get(b) - map.get(a));\n for(int key : map.keySet()){ maxheap.add(key); }\n \n int ans[] = new int[k];\n for(int i = 0; i < k; i++){\n ans[i] = maxheap.poll();\n }\n \n return ans; \n }\n}\n```\n***EXPALANTION OF THE COMPARERATOR FUCTION***\n\n(a,b) -> map.get(b) - map.get(a) is a lambda expression, Also known as a comparator.\n\nIt\'s defining the \'priority\' of the queue to be whichever number ( a or b ) is bigger.\n\nIt works like this...\n\nIf (a,b) -> map.get(b) - map.get(a) - It will start adding elements with their freq in decreasing order (in this case, it will be 3 2 1 (freq))\nif (a,b) -> map.get(a) - map.get(b) - It will start adding element with their freq in increasing order (in this case, it will be 1 2 3 (freq))\n\n// Since you are always doing map.get, it means you\'re comparing it on values only, so doesn\'t confuse it with whatever is written in the key\n\nLets understand this by an example:\n\n```\n// "static void main" must be defined in a public class.\npublic class Main {\n public static void main(String[] args) {\n HashMap<Integer,Integer> map = new HashMap<>();\n \n map.put(1,5);\n map.put(3,8);\n map.put(2,4);\n map.put(4,7);\n \n PriorityQueue<Integer> maxHeap = new PriorityQueue((a,b) -> map.get(b) - map.get(a));\n \n for(int key : map.keySet()) maxHeap.add(key);\n \n System.out.println(maxHeap);\n }\n}\n```\nThe output will be\n```\n[3, 4, 1, 2]\n```\nCREDIT -@captain__aman__\n<hr>\n<hr>\n\n***TIME COMPLEXITY = O(KlogN)***\n\n***SPACE COMPLEXITY =O(N)***\n\n<hr>\n<hr>
36
0
['Heap (Priority Queue)', 'Java']
6
top-k-frequent-elements
[Javascript/Python] Crystal Clear explanation with Animation
javascriptpython-crystal-clear-explanati-xslu
Please dont downvote guys if cannot support,We are putting lot of effort in it\uD83D\uDE42\n\n\nWhat the Question asking us to do \uD83E\uDD14 ?\n Given an i
mageshyt
NORMAL
2022-04-09T04:59:10.991878+00:00
2022-04-09T04:59:10.991909+00:00
5,065
false
**Please dont downvote guys if cannot support,We are putting lot of effort in it\uD83D\uDE42**\n\n```\nWhat the Question asking us to do \uD83E\uDD14 ?\n Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n\n Approach Explanation :\n 1. we will create hashmap to count the frequency of the number\n 2. we will create a new array to store the k most frequent elements\n 3. we will find the frequency of the number and store it in the hashmap\n 4. we will iterate through the hashmap and store the k most frequent elements in the new array\n 5. we will return the new array\nBig o:\n n-->size of the nums\n Time: O(n)\n Space: O(n+n) --> O(n)\n```\n\n![image](https://assets.leetcode.com/users/images/3ba7b529-a07e-4341-a74b-e753f10df3bd_1649479963.2376068.gif)\n\n\n\n`Javascript`\n\n```\nconst topKFrequent = (nums, k) => {\n const map = new Map(); //! map to count the frequency of the number\n for (let num of nums) {\n map.set(num, map.get(num) + 1 || 1);\n }\n const result = [];\n for (let [key, value] of map) {\n result.push([key, value]); //! we will add the number and its frequency\n }\n result.sort((a, b) => b[1] - a[1]); //! we will solve with respect to the frequency of the number\n return result.slice(0, k).map((x) => x[0]); //! we will slice the list with respect to length of k\n};\n```\n\n`Python`\n\n```\nclass Solution:\n def topKFrequent(self, nums, k) :\n map=Counter(nums) # counter is used to count the frequency of each element\n result=[]\n for key,value in map.items():\n result.append([key,value])\n result.sort(key=lambda x:x[1],reverse=True) # sort with respect to the second element in the list\n return [x[0] for x in result[:k]] # return the first k elements in the list\n\n```\n\n\n`UPVOTE if you like \uD83D\uDE03 , If you have any question, feel free to ask.`\n
34
0
['Python', 'JavaScript']
7
top-k-frequent-elements
Five efficient solutions in C++, well-explained
five-efficient-solutions-in-c-well-expla-oayc
Solutions\n\n#### MaxHeap\nSimply, we can just use map to count each distinct number and then insert them all into a priority_queue. The time complexity will be
lhearen
NORMAL
2016-08-17T09:04:53.315000+00:00
2018-10-24T06:37:08.886600+00:00
6,829
false
### Solutions\n\n#### MaxHeap\nSimply, we can just use map to count each distinct number and then insert them all into a priority_queue. The time complexity will be O(klogk) where k is the number of the distinct numbers.\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) \n {\n vector<int> v;\n unordered_map<int, int> count_map;\n for(auto n: nums) count_map[n]++;\n priority_queue<pair<int, int>> maxHeap;\n for(auto& pair: count_map) maxHeap.emplace(pair.second, pair.first);\n while(k--)\n {\n v.push_back(maxHeap.top().second);\n maxHeap.pop();\n }\n return v;\n }\n};\n```\n\n#### MinHeap\nActually, we can also solve this using minimal heap which will remove the least frequent if the size of the minimal heap is larger than k, ensuring the top most k frequent will be stored in the minimal heap in the end.\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) \n {\n vector<int> v;\n unordered_map<int, int> count_map;\n for(auto n: nums) count_map[n]++;\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int,int>>> minHeap;\n for(auto& pair: count_map) \n {\n minHeap.emplace(pair.second, pair.first);\n if(minHeap.size() > k) minHeap.pop();\n }\n while(k--)\n {\n v.push_back(minHeap.top().second);\n minHeap.pop();\n }\n return v;\n }\n};\n```\n\n#### Multimap\n\nUsing multimap to sort the numbers by its frequency and to accelerate the collecting process, we can adopt set to collect the frequencies for each number and then collect from the most frequent to the least.\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) \n {\n vector<int> v;\n unordered_map<int, int> keys_map;\n for(auto n: nums) keys_map[n]++;\n multimap<int,int> count_map;\n set<int> count_set;\n for(auto& pair: keys_map) count_set.insert(pair.second), count_map.emplace(pair.second, pair.first);\n for(auto count_iter=count_set.rbegin(); count_iter!=count_set.rend(); ++count_iter)\n {\n int i = *count_iter;\n if(count_map.count(i))\n {\n for(auto iter = count_map.equal_range(i).first; iter != count_map.equal_range(i).second; ++iter)\n {\n v.push_back(iter->second);\n if(v.size() == k) return v;\n }\n }\n }\n return v;\n }\n};\n```\n\n#### Vector\nActually the previous solution can be simplified with vector but we then have to traverse all the possible frequency instead of that just appear (count_set used in the previous solution).\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) \n {\n vector<int> v;\n if(nums.empty()) return v;\n unordered_map<int, int> keys_map;\n for(auto n: nums) keys_map[n]++;\n vector<vector<int>> buckets(nums.size()+1);\n for(auto& pair: keys_map) buckets[pair.second].push_back(pair.first);\n for(int i = nums.size(); i; --i)\n {\n for(int j = 0; j < buckets[i].size(); ++j)\n {\n v.push_back(buckets[i][j]);\n if(v.size() == k) return v;\n }\n }\n return v;\n }\n};\n```\n\n#### Array\nCounting the frquency count and through these values, we can swiftly locate the frquency count which separate the top k most frequent numbers from the rest. We cannot use lower_bound to locate it, because the index and the frequency count is not one-to-one.\n\nSo the following method won't work; and arr here is a vector format of cumulative.\n`int kCount = lower_bound(arr.rbegin(), arr.rend(), k)-upper_bound(arr.rbegin(), arr.rend(), 0)+1;`\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) \n {\n vector<int> v;\n if(nums.empty()) return v;\n int cumulative[nums.size()+1] = {0};\n unordered_map<int, int> keys_map;\n for(auto n: nums) cumulative[keys_map[n]++]++;\n int kCount = 0;\n for(int i = nums.size(); i; --i) if(cumulative[i]>=k) { kCount = i; break; }\n for(auto& pair: keys_map) \n if(pair.second > kCount) v.push_back(pair.first);\n if(v.size() == k) return v;\n for(auto& pair: keys_map) \n {\n if(pair.second == kCount) v.push_back(pair.first);\n if(v.size() == k) return v;\n }\n return v;\n }\n};\n```\n\nAlways welcome new ideas and `practical` tricks, just leave them in the comments!
34
4
['C']
4
top-k-frequent-elements
Three C++ solutions (MaxHeap / MinHeap / Bucket Sort)
three-c-solutions-maxheap-minheap-bucket-cajt
Solution 1. MaxHeap, O(nlogn).\n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int>m;\n
zefengsong
NORMAL
2017-07-10T07:42:47.559000+00:00
2017-07-10T07:42:47.559000+00:00
2,959
false
**Solution 1.** MaxHeap, O(nlogn).\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int>m;\n for(auto x: nums) m[x]++;\n priority_queue<pair<int, int>>pq;\n for(auto p: m) pq.push({p.second, p.first});\n vector<int>res;\n while(k--) res.push_back(pq.top().second), pq.pop();\n return res;\n }\n};\n```\n***\nO(nlog(n - k)).\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int>m;\n for(auto x: nums) m[x]++;\n priority_queue<pair<int, int>>pq;\n vector<int>res;\n for(auto p: m){\n pq.push({p.second, p.first});\n if(pq.size() > m.size() - k){\n res.push_back(pq.top().second);\n pq.pop();\n }\n }\n return res;\n }\n};\n```\n***\n**Solution 2.** MinHeap, O(nlogk).\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int>m;\n for(auto x: nums) m[x]++;\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>pq;\n for(auto p: m){\n pq.push({p.second, p.first});\n if(pq.size() > k) pq.pop();\n }\n vector<int>res;\n while(k--) res.push_back(pq.top().second), pq.pop();\n return res;\n }\n};\n```\n***\n**Solution 3.** Bucket Sort, O(n).\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int>m;\n for(auto x: nums) m[x]++;\n vector<int>res;\n vector<vector<int>>bucket(nums.size() + 1);\n for(auto p: m) bucket[p.second].push_back(p.first);\n for(int i = bucket.size() - 1; res.size() < k; i--)\n for(auto j: bucket[i]) res.push_back(j);\n return res;\n }\n};\n```
34
0
['C++']
5
top-k-frequent-elements
Python - heap
python-heap-by-ypmagic2-5lxg
Don\'t reference ANY python - 2 lines of code solutions. In an interview, if you write Counter.most_common, and the interviewer doesn\'t know python at all, the
ypmagic2
NORMAL
2020-08-13T10:01:15.223998+00:00
2020-08-13T10:01:15.224043+00:00
5,395
false
Don\'t reference ANY python - 2 lines of code solutions. In an interview, if you write Counter.most_common, and the interviewer doesn\'t know python at all, they won\'t understand what is going on.\n\nThe point of the problem is for you to use a priority queue, not use a library that has it done in the background. \n\nYou are inserting at most n elements, and insertion takes log n time. This solution is O(n log n). \n\n```\ndef topKFrequent(self, nums: List[int], k: int) -> List[int]:\n hashmap = {}\n for num in nums:\n if num in hashmap:\n hashmap[num] += 1\n else:\n hashmap[num] = 1\n heap = []\n for key in hashmap:\n heapq.heappush(heap, (-hashmap[key], key))\n \n res = []\n for _ in range(k):\n popped = heapq.heappop(heap)\n res.append(popped[1])\n \n return res\n```
33
1
['Heap (Priority Queue)', 'Python']
6
top-k-frequent-elements
Time Complexity O(N).✔️ Fastest solution✔️✔️
time-complexity-on-fastest-solution-by-i-6t7b
The approach is to first store the key value pair of numbers and their corresponding frequencies in a unordered_map.\nAfter that create a vector freq of size nu
iamdhritiman01
NORMAL
2022-08-15T10:09:05.428557+00:00
2022-08-15T11:18:44.766358+00:00
2,760
false
The approach is to first store the key value pair of numbers and their corresponding frequencies in a unordered_map.\nAfter that create a vector *freq* of size `nums.size()+1` and push the keys of the unordered_map into the vector *freq* considering the index of vector *freq* as the frequency of that key.\nFinally using a reverse for loop, take the top K frequencies from the *freq* vector.\nSo, the time complexity is O(N) and the space complexity is also O(N).\n\n\u2714\uFE0FPlease **upvote** if you liked the solution\u2714\uFE0F\n![image](https://assets.leetcode.com/users/images/c25d4a45-dc09-4f09-afc1-95244b7ca44b_1660562304.2807186.jpeg)\n\n\n\n```\n\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int> umap;\n vector<vector<int>> freq(nums.size()+1);\n vector<int> ans;\n int count=0;\n for(int i=0; i<nums.size(); i++){\n umap[nums[i]]++;\n }\n for(auto e:umap){\n freq[e.second].push_back(e.first);\n }\n for(int i=nums.size(); i>0; i--){\n if(freq[i].size()!=0){\n for(int j=0; j<freq[i].size(); j++){\n ans.push_back(freq[i][j]);\n count++;\n }\n }\n if(count==k) break;\n }\n return ans;\n }\n};\n```
32
0
[]
2
top-k-frequent-elements
[JavaScript] sorted hashMap | beats 98%
javascript-sorted-hashmap-beats-98-by-ha-s537
\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar topKFrequent = function(nums, k) {\n let res = [], map = new Map();\n
haleyysz
NORMAL
2019-06-08T09:36:52.099022+00:00
2019-06-08T09:48:25.618685+00:00
7,400
false
```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar topKFrequent = function(nums, k) {\n let res = [], map = new Map();\n \n nums.forEach(n => map.set(n, map.get(n) + 1 || 1));\n \n let sortedArray = [...map.entries()].sort((a, b) => b[1] - a[1]);\n \n for(let i = 0; i < k; i++) {\n res.push(sortedArray[i][0]);\n }\n \n return res;\n};\n```
32
8
['JavaScript']
8
top-k-frequent-elements
JavaScript Clean Bucket Sort Solution
javascript-clean-bucket-sort-solution-by-itkr
javascript\nconst topKFrequent = (nums, k) => {\n const map = {};\n const result = [];\n const bucket = Array(nums.length + 1).fill().map(() => []);\n
jeantimex
NORMAL
2018-07-15T06:46:14.423602+00:00
2018-08-16T14:37:42.076071+00:00
4,095
false
```javascript\nconst topKFrequent = (nums, k) => {\n const map = {};\n const result = [];\n const bucket = Array(nums.length + 1).fill().map(() => []);\n \n for (let num of nums) {\n map[num] = ~~map[num] + 1;\n }\n \n for (let num in map) {\n bucket[map[num]].push(parseInt(num));\n }\n \n for (let i = nums.length; i >= 0 && k > 0; k--) {\n while (bucket[i].length === 0) i--;\n result.push(bucket[i].shift());\n }\n \n return result;\n};\n```
28
0
[]
6
top-k-frequent-elements
C++ | Minheap | Well Commented
c-minheap-well-commented-by-abhi_vee-el3w
\nWe have declared a priority queue that will work as min heap, an unordered map and a res vector for result . Lets take an example and see the working of code.
abhi_vee
NORMAL
2021-08-22T07:41:50.618993+00:00
2021-08-22T07:43:11.975070+00:00
3,188
false
```\nWe have declared a priority queue that will work as min heap, an unordered map and a res vector for result . Lets take an example and see the working of code.\nEg: nums = 1,1,1,2,2,3 and k = 2\nTraverse the nums vector and fill the map with frequency of occurence of elements in nums\nso we will get mp as (3,1), (2,2), (1,3) where key is the element and value is its frequency.\nNow traverse the map till end to fill the minh with key-value as a pair, where key is the frequency (the second part i->second) and value is the element (the first part i->first)\nminh will keep minimum elements at top and maximum frequency elements will be protected at bottom so minh.size() > k will keep popping top elements which are not needed and keep the space complexity of minh to maximum of k value.\nNow we will have minh with key value pairs as (2,2) and (3,1) where first part is the frequency and second part is element, eg: (2,2) means 2 times element 2 has occured in nums and now its stored in minh\nNow simply empty the minheap and push all its elements in res vector. We are pushing second part as we know second part of minheap pair has the element and the first part has frequency.\nSo res will contain [2,1] so return it .\nupvote if u like it .\n```\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n \n priority_queue < pair<int,int> , vector<pair<int,int>> , greater<pair<int,int>> > minh;\n unordered_map <int,int> mp;\n vector <int> res;\n \n for(int i=0; i<nums.size(); i++)\n mp[nums[i]]++;\n \n for(auto i=mp.begin(); i!=mp.end(); i++)\n {\n minh.push({i->second, i->first});\n if(minh.size() > k)\n minh.pop();\n }\n \n while(minh.size() > 0)\n {\n res.push_back(minh.top().second);\n minh.pop();\n }\n \n return res;\n }\n};\n```
27
0
['C', 'Heap (Priority Queue)', 'C++']
2
top-k-frequent-elements
Java 6 lines HashMap Collections.sort easy to understand with Explaination
java-6-lines-hashmap-collectionssort-eas-9628
\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n // build map<num, frequence>\n Map<Integer, Integer> map = new HashMap<In
coolmike
NORMAL
2021-01-26T16:33:59.800070+00:00
2021-01-26T16:33:59.800107+00:00
2,229
false
```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n // build map<num, frequence>\n Map<Integer, Integer> map = new HashMap<Integer, Integer>();\n for (int num: nums) map.put(num, map.getOrDefault(num, 0) + 1);\n \n // sort list from map.keyset() by map.get(num),\n List<Integer> list = new ArrayList<>(map.keySet());\n Collections.sort(list, (a, b) -> map.get(b) - map.get(a));\n \n // transfer results from list to int[];\n int[] res = new int[k];\n for (int i = 0; i < k; i++) res[i] = list.get(i);\n \n return res;\n }\n}\n```
25
0
['Java']
0
top-k-frequent-elements
Python O(n) solution: dictionary + quick select
python-on-solution-dictionary-quick-sele-xdkd
I used a dictionary to get the frequencies, and then used quick select to get the top k frequenct elements.\n\n def topKFrequent(nums, k):\n \n
nahgnaw
NORMAL
2016-05-02T05:06:53+00:00
2018-10-12T19:49:54.687987+00:00
11,773
false
I used a dictionary to get the frequencies, and then used quick select to get the top k frequenct elements.\n\n def topKFrequent(nums, k):\n \n def quick_select(left, right):\n pivot = left\n l, r = left, right\n while l < r:\n while l < r and counts[r][1] <= counts[pivot][1]:\n r -= 1\n while l < r and counts[l][1] >= counts[pivot][1]:\n l += 1\n counts[l], counts[r] = counts[r], counts[l]\n counts[left], counts[l] = counts[l], counts[left]\n \n if l + 1 == k:\n return counts[:l+1]\n elif l + 1 < k:\n return quick_select(l + 1, right)\n else:\n return quick_select(left, l - 1)\n \n if not nums:\n return []\n \n # Get the counts.\n counts = {}\n for x in nums:\n counts[x] = counts.setdefault(x, 0) + 1\n \n counts = counts.items()\n # Use quick select to get the top k counts.\n return [c[0] for c in quick_select(0, len(counts) - 1)]
25
0
['Quickselect', 'Python']
2
top-k-frequent-elements
Java. A simple accepted solution.
java-a-simple-accepted-solution-by-franc-g1eh
Use hashmap to store the count. \n\n Map countMap = new HashMap<>();\n List ret = new ArrayList<>();\n for (int n : nums) {\n if (co
francisyang1991
NORMAL
2016-05-02T02:35:14+00:00
2016-05-02T02:35:14+00:00
12,137
false
Use hashmap to store the count. \n\n Map<Integer, Integer> countMap = new HashMap<>();\n List<Integer> ret = new ArrayList<>();\n for (int n : nums) {\n if (countMap.containsKey(n)) {\n countMap.put(n ,countMap.get(n)+1);\n } else {\n countMap.put(n ,1);\n }\n }\n PriorityQueue<Map.Entry<Integer, Integer>> pq =\n new PriorityQueue<Map.Entry<Integer, Integer>>((o1, o2) -> o2.getValue() - o1.getValue());\n pq.addAll(countMap.entrySet());\n \n List<Integer> ret = new ArrayList<>();\n for(int i = 0; i < k; i++){\n ret.add(pq.poll().getKey());\n }\n return ret;
25
2
['Java']
6
top-k-frequent-elements
Concise solution O(n + klogn) python using minheap and dict
concise-solution-on-klogn-python-using-m-e43x
Uses a dict to maintain counts, heapifys the list of counts, then selects K elements out of the max heap. \n\n import heapq\n \n class Solution(object)
kynes
NORMAL
2016-05-12T22:15:19+00:00
2018-10-12T19:49:29.126535+00:00
6,188
false
Uses a dict to maintain counts, heapifys the list of counts, then selects K elements out of the max heap. \n\n import heapq\n \n class Solution(object):\n def topKFrequent(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n """\n freq = {}\n freq_list=[] \n for num in nums:\n if num in freq:\n freq[num] = freq[num] + 1\n else:\n freq[num] = 1\n \n for key in freq.keys():\n \n freq_list.append((-freq[key], key))\n heapq.heapify(freq_list)\n topk = []\n for i in range(0,k):\n topk.append(heapq.heappop(freq_list)[1])\n return topk
25
1
[]
5
top-k-frequent-elements
347: Time 91.58%, Solution with step by step explanation
347-time-9158-solution-with-step-by-step-17t7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThis problem can be solved by using a hash map to count the frequency of
Marlen09
NORMAL
2023-03-02T05:47:21.678247+00:00
2023-03-02T05:47:21.678288+00:00
11,687
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis problem can be solved by using a hash map to count the frequency of each element in the array. Then we can use a min-heap to store the top k frequent elements. The heap is ordered by the frequency of the elements, with the smallest frequency at the top of the heap. If we encounter an element with a frequency greater than the top of the heap, we remove the top element and insert the new element into the heap. Finally, we return the elements in the heap.\n\n# Complexity\n- Time complexity:\n91.58%, O(n log k), where n is the length of the input array and k is the number of unique elements in the array.\n\n- Space complexity:\n88.75%, O(n), where n is the length of the input array.\n\n# Code\n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n # Step 1: Count the frequency of each element using a hash map\n freq = {}\n for num in nums:\n freq[num] = freq.get(num, 0) + 1\n \n # Step 2: Use a min-heap to store the top k frequent elements\n heap = []\n for num, count in freq.items():\n if len(heap) < k:\n heapq.heappush(heap, (count, num))\n elif count > heap[0][0]:\n heapq.heappop(heap)\n heapq.heappush(heap, (count, num))\n \n # Step 3: Return the elements in the heap\n return [num for count, num in heap]\n\n```
24
0
['Array', 'Hash Table', 'Divide and Conquer', 'Python', 'Python3']
9
top-k-frequent-elements
Cool Java stream approach🔥
cool-java-stream-approach-by-alexei7a-mzjx
Approach\nIterate through stream:\n- Create map using Collectors.groupingBy(Function.identity(), Collectors.counting()\n- Sort it by map values\n- limit it to k
alexei7a
NORMAL
2023-03-23T09:29:07.379964+00:00
2023-03-23T09:29:07.379994+00:00
3,136
false
# Approach\nIterate through stream:\n- Create map using `Collectors.groupingBy(Function.identity(), Collectors.counting()`\n- Sort it by map values\n- limit it to `k` elements\n- return it back\n# Complexity\n- Time complexity:\nO(n*logn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n return Arrays.stream(nums)\n .boxed()\n .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))\n .entrySet()\n .stream()\n .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))\n .limit(k)\n .mapToInt(Map.Entry::getKey)\n .toArray();\n }\n}\n```
23
1
['Ordered Map', 'Data Stream', 'Java']
6
top-k-frequent-elements
🔥✅✅ Beat 96.13% | ✅ Full Explanation ✅✅🔥
beat-9613-full-explanation-by-devogabek-uy87
\nClick here to see the submitted\n\n[![Screen Shot 2024-03-22 at 19.41.14.png](https://assets.leetcode.com/users/images/1d23ec94-54a2-4f18-afd9-1785269cfe8c_17
DevOgabek
NORMAL
2024-03-22T14:43:09.371905+00:00
2024-03-22T14:43:34.406585+00:00
16,021
false
<details>\n<summary><b>Click here to see the submitted</b></summary>\n\n[![Screen Shot 2024-03-22 at 19.41.14.png](https://assets.leetcode.com/users/images/1d23ec94-54a2-4f18-afd9-1785269cfe8c_1711118500.4429057.png)](https://leetcode.com/problems/top-k-frequent-elements/submissions/1210933053?envType=study-plan-v2&envId=top-100-liked)\n</details>\n\n\n![Screen Shot 2024-03-14 at 11.30.19 2.png](https://assets.leetcode.com/users/images/9dc1665e-7eab-4153-9fc7-61985831b62b_1711116370.6052735.png)\n\n![Screen Shot 2024-03-14 at 11.30.19 2 2.png](https://assets.leetcode.com/users/images/f82eaf01-dc34-454b-b71d-b71eb5dc4977_1711117975.775304.png)\n\n\n<details>\n<summary><b>Click here to see the text explanation</b></summary>\n<br>\n<br>\n\n1. It imports the `collections` module, which provides specialized container datatypes.\n2. It defines the `most_common_elements` function which takes two parameters:\n - `nums`: a list of numbers.\n - `k`: an integer representing the number of most common elements to find.\n3. Inside the function, it creates a `Counter` object from the `collections` module by passing the `nums` list to it. The `Counter` object counts the occurrences of each element in the list.\n4. It then uses the `most_common()` method of the `Counter` object to retrieve the `k` most common elements along with their counts. This method returns a list of tuples, where each tuple contains an element and its count, sorted in descending order by count.\n\n5. Finally, it constructs and returns a list containing only the elements from the tuples, discarding their counts. This list contains the `k` most common elements in the original list `nums`.\n</details>\n\n<br>\n<br>\n\n```python []\nclass Solution(object):\n def topKFrequent(self, nums, k):\n counter = Counter(nums)\n return [num for num, _ in counter.most_common(k)]\n```\n```python3 []\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n counter = Counter(nums)\n return [num for num, _ in counter.most_common(k)]\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> counter;\n for (int num : nums) {\n counter[num]++;\n }\n \n vector<pair<int, int>> sorted(counter.begin(), counter.end());\n sort(sorted.begin(), sorted.end(), [](const pair<int, int>& a, const pair<int, int>& b) {\n return a.second > b.second;\n });\n \n vector<int> result;\n for (int i = 0; i < k && i < sorted.size(); ++i) {\n result.push_back(sorted[i].first);\n }\n return result;\n }\n};\n```\n```javascript []\nvar topKFrequent = function(nums, k) {\n let counter = new Map();\n nums.forEach(num => {\n counter.set(num, (counter.get(num) || 0) + 1);\n });\n let sorted = Array.from(counter.entries()).sort((a, b) => b[1] - a[1]);\n return sorted.slice(0, k).map(entry => entry[0]);\n};\n```\n\n![Screen Shot 2024-03-14 at 11.30.19.png](https://assets.leetcode.com/users/images/99fe0b15-b318-4601-af0f-574bc98640ee_1710652249.4421208.png)
22
4
['Array', 'Hash Table', 'Sorting', 'Heap (Priority Queue)', 'Counting', 'Quickselect', 'Python', 'C++', 'Python3', 'JavaScript']
10
top-k-frequent-elements
10 lines in Java | Easy Solution
10-lines-in-java-easy-solution-by-srikan-xfbk
Approach\n- HashMap | Sorting\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\n- O(nlogn)\n Add your time complexity here
srikanth-rl
NORMAL
2023-10-13T08:02:42.820757+00:00
2024-01-08T07:02:54.643732+00:00
6,393
false
## Approach\n- **HashMap | Sorting**\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n**- Time complexity:**\n- $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n**- Space complexity:**\n- $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int i : nums)\n map.merge(i, 1, Integer::sum);//For Getting Frequency\n List<Integer> list = new ArrayList<>(map.keySet());\n list.sort((a, b) -> map.get(b) - map.get(a)); //Sort by Frequency in descending order \n int res[] = new int[k];\n for (int i = 0; i < k; ++i)\n res[i] = list.get(i);\n return res;\n }\n}\n
22
1
['Hash Table', 'Java']
3
top-k-frequent-elements
✅JS | Explained with comments | O(n) Solution✅
js-explained-with-comments-on-solution-b-q2i6
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
krushna_sharma
NORMAL
2023-01-29T16:10:53.341673+00:00
2023-01-29T16:10:53.341714+00:00
4,610
false
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar topKFrequent = function(nums, k) {\n // Create an empty hash map to store the frequency of each element in the array\n let hm = {};\n // Create an empty array to store the elements based on their frequency\n const freq = Array.from({ length: nums.length + 1 }, () => 0);\n // Iterate through the input array and add the frequency of each element to the hash map\n for (const num of nums) {\n hm[num] = (hm[num] || 0) + 1;\n }\n // Iterate through the hash map and add the elements to the frequency array based on their frequency\n for (const key in hm) {\n freq[hm[key]] = (freq[hm[key]] || []).concat(key);\n }\n // Create an empty array to store the top k frequent elements\n let ans = [];\n // Iterate through the frequency array from the highest frequency to the lowest\n for (let j = freq.length - 1; j >= 0; j--) {\n // If the current frequency array is not empty, add the elements to the ans array\n // and decrement k until k is 0 or the frequency array is empty\n for (let i = 0; i < freq[j].length && k > 0; i++) {\n ans.push(Number(freq[j][i]));\n k--;\n }\n }\n return ans;\n};\n\n```\n\n![cutecat](https://assets.leetcode.com/users/images/a368e607-130a-49ea-a1b8-58402aeb1cbf_1674878823.1172526.jpeg)
22
0
['Array', 'Hash Table', 'Bucket Sort', 'JavaScript']
1
top-k-frequent-elements
Time Complexity O(N). Fastest Python Solution 🚀🚀🚀 Bucket Sort
time-complexity-on-fastest-python-soluti-rect
Bucket Sort Implementation\nBelow is a bucket sort implementation in python, running in with a time complexity O(N). Our buckets correspond the lists in our lis
AMerii
NORMAL
2022-08-17T11:15:12.684823+00:00
2022-08-17T11:20:43.587680+00:00
3,272
false
# Bucket Sort Implementation\nBelow is a bucket sort implementation in python, running in with a time complexity O(N). Our buckets correspond the lists in our list of lists.\n\n```\nfrom collections import defaultdict\n\ndef topKFrequent(nums: list[int], k: int):\n num_count = defaultdict(int)\n\n if k == len(nums):\n return nums\n\n # create hashmap of containing the count of each number\n for num in nums:\n num_count[num] += 1\n\n # create a list of lists to store the counts of in the correct order\n bucket_list = [[] for i in range(len(nums))]\n\n # store the numbers in the bucket list using the count as the index\n for num,count in num_count.items():\n bucket_list[count-1].append(num) # we subtract 1 since, the smallest index in our list "0" corresponds to the smallest possible count which is "1"\n\n # unpack the bucket list into a new list\n results = []\n for bucket in bucket_list:\n results.extend(bucket)\n\n # fetch the top k elements by iterating through the list in reverse (since we want the max count)\n topk = []\n for i in range(-1,-(k+1),-1): # we add 1 to k, since we k+1 will not be included\n topk.append(l[i])\n\n return topk\n```\n\nNote that the solution above can be shortened, however I thought it would be useful to keep it this way to improve readability.\n\nAlso, below is a helpful visualization from [another post implemented in java](https://leetcode.com/problems/top-k-frequent-elements/discuss/2428568/Time-Complexity-O(N).-Fastest-solution) by [@iamdhritiman01](https://leetcode.com/iamdhritiman01/), check out his post and upvote it if you found it helpful!\n\n![image](https://assets.leetcode.com/users/images/630037d7-6585-4ed3-a86c-40581bdae7d4_1660734874.965491.png)\n\n\n\uD83D\uDE80\uD83D\uDE80\uD83D\uDE80 If you found this helpful please don\'t forget to upvote! \uD83D\uDE80\uD83D\uDE80\uD83D\uDE80
22
0
['Bucket Sort', 'Python']
1
top-k-frequent-elements
JAVA Solution to get top k elements coming in a stream instead of knowing array earlier
java-solution-to-get-top-k-elements-comi-rhwa
Explanation: Let\'s assume we have a stream of arrays, and the following assumption still holds true that k will always be within the range [1,unique number of
gargnisha
NORMAL
2020-05-12T14:17:45.091787+00:00
2022-04-23T12:50:23.481193+00:00
5,468
false
**Explanation**: Let\'s assume we have a stream of arrays, and the following assumption still holds true that k will always be within the range [1,unique number of elements in the array].\n\nLets\'s take the following operations and K=2\na) Add 1\nb) Add 1\nc) Add 2\nd) Find top 2 elements\ne) Add 3\nf) Find top 2 elements\ng) Add 2\nh) Find top 2 elements\n\n**For operation a, b and c**, we add the values in heap - it\'s a min heap, so heap would have "1" and "2" element.\nAlso, priority of heap is the frequency of each element.\nSo presentInHeap map: [1 : 2, 2:1]\n1:2 -> means "1" is added and its frequency is 2\n2:1 -> means "2" is added and its frequency is 1\n**For operation d** - we can print top 2 element from the heap \n**For operation e**- "3" is added in the map but 2 will be popped out since the heap size which becomes 3 now exceeds k=2 \nSo now, we will delete "2" from the main heap but maintain the notInHeap map with popped value\nnotInHeap map: [2 :1] , it means that when 2 was popped out from main heap, its frequency so far encountered is 1.\n**For operation f** - Top 2 elements would be "1" and "3"\n**For operation g** - Add "2", since 2 is not there in the heap, hence it add the element in the heap, by getting the frequency from notInHeap map\n```\npresentInHeap.put(element,notInHeap.getOrDefault(element,0) + 1);\n```\n\nThis gives the final frequency as 2 for "2" value.\nSo now heap has total three elements:\n1 with frequency 2\n2 with frequency 2\n3 with frequency 1\n\nSo now, "3" gets popped out from main heap and pushed in notInHeap map\n\n**For operation h**: find top 2 elements from the heap which is "1" and "2".\n\n**I hope it explains the approach :)**\n\n**One minor correction** : It seems we are adding the entire nums at once, but we can change and call this function as we are getting elements in a stream. That is whenever we get any input, then call the addInHeap method and call the getTopKElementsFromHeap to find the top K elements at any point of time in a stream.\n``` \nfor(int i=0;i<nums.length;i++){\n addInHeap(presentInHeap,notInHeap,heap, k,nums[i]);\n}\n```\n\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n \n Map<Integer,Integer> presentInHeap = new HashMap<>();\n Map<Integer,Integer> notInHeap = new HashMap<>();\n \n PriorityQueue<Integer> heap = new PriorityQueue<>(\n (a,b) -> presentInHeap.getOrDefault(a,0) - presentInHeap.getOrDefault(b,0) );\n \n\t\t// For n elements, adding into heap will take O(K) time, hence the total complexity would be O(nk)\n for(int i=0;i<nums.length;i++){\n addInHeap(presentInHeap,notInHeap,heap, k,nums[i]);\n }\n return getTopKElementsFromHeap(heap);\n }\n \n \n public void addInHeap(Map<Integer,Integer> presentInHeap,\n Map<Integer,Integer> notInHeap,\n PriorityQueue<Integer> heap,\n int k,\n int element){\n \n if(presentInHeap.containsKey(element)){\n presentInHeap.put(element,presentInHeap.get(element)+1);\n\t\t\t// O(k) since for removing the element, all the elements has to be scanned.\n heap.remove(element);\n\t\t\t// O(log K) for adding the element and for heapify operation.\n heap.add(element);\n }else{\n presentInHeap.put(element,notInHeap.getOrDefault(element,0) + 1);\n\t\t\t// O(log K) for adding the element and for heapify operation.\n heap.add(element);\n if(heap.size() > k){\n int poppedElement = heap.poll(); // O(K) for removing the top element and heapify operation.\n notInHeap.put(poppedElement,presentInHeap.get(poppedElement));\n presentInHeap.remove(poppedElement);\n }\n }\n }\n \n public int[] getTopKElementsFromHeap(PriorityQueue<Integer> heap){\n int i=0;\n int topKElements[] = new int[heap.size()];\n for(Integer element: heap){\n topKElements[i++] = element;\n }\n return topKElements;\n }\n}\n```
22
0
[]
12
top-k-frequent-elements
Python - 3 Ways w/ Explanation
python-3-ways-w-explanation-by-noobie12-jssc
IDEA 1: Create a Counter object for \'nums\' and return the \'k\' most common keys\n\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n
noobie12
NORMAL
2020-07-18T07:21:35.852014+00:00
2020-07-18T07:21:35.852052+00:00
5,491
false
IDEA 1: Create a Counter object for \'nums\' and return the \'k\' most common keys\n```\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n return [key for key, _ in collections.Counter(nums).most_common(k)]\n```\n\nIDEA 2: Create a max heap for the Counter object and then return the top \'k\' elements by popping from the heap \'k\' times. \n```\n def topKFrequent_heap(self, nums: List[int], k: int) -> List[int]:\n result = []\n max_heap = [(-val, key) for key,val in collections.Counter(nums).items()]\n heapq.heapify(max_heap)\n for _ in range(k):\n result.append(heapq.heappop(max_heap)[1])\n return result\n```\n\nIDEA 3: Use Bucket Sort to create buckets of frequencies where the elements with same frequencies of occurence are all stored in the same bucket. We then use these buckets to build the result list by iterating over the frequencies in reverse order. (Frequencies range from 0 to len(nums), it\'s quite intuitive)\n\n```\n def topKFrequent_bucket(self, nums: List[int], k: int) -> List[int]:\n frequency, result = collections.Counter(nums), []\n inv_frequency = collections.defaultdict(list)\n # Filling up the buckets -> frequency to item mapping\n # frequency : List[List[int]]\n for key, freq in frequency.items():\n inv_frequency[freq].append(key)\n # Buckets will have frequency range from 0 to len(nums). \n\t\t# Thus, we find valid frequencies i.e. those with entries\n for i in range(len(nums), 0, -1):\n result.extend(inv_frequency[i])\n if len(result) >= k:\n break\n return result[:k]\n```\n\nIf this answer helped you, please upvote!\nIf you have improvements, please comment below! :)
21
0
['Heap (Priority Queue)', 'Bucket Sort', 'Python3']
2
top-k-frequent-elements
[javascript] [hash map] [sort] [priority queue] solution
javascript-hash-map-sort-priority-queue-va2ee
1) O(N Log N) - PriorityQueue: a) O(N) to build a map; b) O(Log N) for PriorityQueue operations\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @re
alioshka
NORMAL
2020-01-14T21:08:09.160387+00:00
2023-11-09T23:43:46.391651+00:00
4,461
false
1) **O(N Log N) - PriorityQueue:** a) O(N) to build a map; b) O(Log N) for PriorityQueue operations\n```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar topKFrequent = function(nums, k) {\n // results array\n let results = [];\n \n // 1) first step is to build a hash map, where "element -> its frequency"\n // it costs O(N), where n is nums.length\n let map = {};\n nums.forEach(n => map[n] ? map[n] += 1 : map[n] = 1);\n \n let pq = new PriorityQueueImpl();\n // 2) enqueue each map element to max binary heap priority queue\n for(let key in map){\n pq.enqueue(key, map[key]); // pq.enqueue costs O(log N), where n is nums.length\n }\n \n // 3) k times dequeue element from priority queue and push it to results array\n for(let i = 0; i < k; i++){\n results.push(pq.dequeue()); // pq.dequeue() costs O(log N), where n is nums.length\n }\n \n // return results array\n\t// as result we have O(N Log N) where n is length of nums\n return results;\n};\n\nclass PriorityQueueImpl {\n constructor(){\n this._values = [];\n }\n \n enqueue(val, priority){\n this._values.push(new Node(val, priority));\n this._traverseUp();\n }\n \n dequeue(){\n const max = this._values[0];\n const end = this._values.pop();\n if(this._values.length > 0){\n this._values[0] = end;\n this._traverseDown();\n }\n return max.val;\n \n }\n \n _traverseUp(){\n let idx = this._values.length - 1;\n const el = this._values[idx];\n while(idx > 0){\n let pIdx = Math.floor((idx - 1) / 2);\n let parent = this._values[pIdx];\n if(el.priority <= parent.priority) break;\n this._values[pIdx] = el;\n this._values[idx] = parent;\n idx = pIdx;\n }\n }\n \n _traverseDown(){\n let leftChildIdx = null;\n let rightChildIdx = null;\n let leftChild = null;\n let rightChild = null;\n let swapIdx = null;\n \n let idx = 0;\n const el = this._values[idx];\n while(true){\n swapIdx = null;\n leftChildIdx = 2 * idx + 1;\n rightChildIdx = 2 * idx + 2;\n \n if(leftChildIdx < this._values.length){\n leftChild = this._values[leftChildIdx];\n if(leftChild.priority > el.priority){\n swapIdx = leftChildIdx;\n }\n }\n \n if(rightChildIdx < this._values.length){\n rightChild = this._values[rightChildIdx];\n if(\n (swapIdx === null && rightChild.priority > el.priority) ||\n (swapIdx !==null && rightChild.priority > leftChild.priority)\n ) {\n swapIdx = rightChildIdx;\n }\n }\n \n if(swapIdx === null) break;\n this._values[idx] = this._values[swapIdx];\n this._values[swapIdx] = el;\n idx = swapIdx\n }\n }\n}\n\nclass Node {\n constructor(val, priority){\n this.val = val;\n this.priority = priority;\n }\n}\n```\nalso there is one more simple solution that actually has same time coplexity:\n2) **O(N log N) - Map and Sort**: a) O(N) to build a map; b) O(N Log N) for sort\n```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar topKFrequent2 = function(nums, k) {\n // results array\n let results = [];\n \n // 1) first step is to build a hash map, where "element -> its frequency"\n // it costs O(N), where n is nums.length\n let map = {};\n nums.forEach(n => map[n] ? map[n] += 1 : map[n] = 1);\n \n // 2) sort the map keys array based on its frequency\n // it costs O(N log N), where n is nums.length\n let sortedKeys = Object.keys(map).sort((a,b)=>map[b]-map[a]);\n \n // 3) take first k results\n for(let i = 0; i < k; i++){\n results.push(sortedKeys[i]);\n }\n \n // as result we have O(N Log N) where n is length of nums\n return results;\n};\n```
21
0
['Heap (Priority Queue)', 'JavaScript']
5
top-k-frequent-elements
Java Priority queue lambda expression
java-priority-queue-lambda-expression-by-vib3
Hey, I just found a concise way to use lambda expression\n\n\nclass Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer,
crazy09
NORMAL
2018-08-05T06:22:18.119218+00:00
2018-08-17T17:34:41.149517+00:00
27,957
false
Hey, I just found a concise way to use lambda expression\n\n```\nclass Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int num: nums) {\n map.put(num, map.getOrDefault(num, 0) + 1);\n }\n PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());\n map.entrySet().forEach(e -> {\n pq.offer(e);\n if (pq.size() > k) {\n pq.poll();\n }\n });\n return pq.stream().map(o -> o.getKey()).collect(Collectors.toList());\n }\n}\n```
20
0
[]
3
top-k-frequent-elements
Best Solution for Arrays 🚀 in C++, Python and Java || 100% working
best-solution-for-arrays-in-c-python-and-vzyb
📚 IntuitionWe need to find the top K most frequent elements in an array. First, let's count how often each number appears and then extract the top K frequent nu
BladeRunner150
NORMAL
2025-01-11T14:31:24.783656+00:00
2025-01-11T14:31:24.783656+00:00
7,362
false
# 📚 Intuition We need to find the **top K most frequent elements** in an array. First, let's count how often each number appears and then extract the top K frequent numbers! 🔥 # 🚀 Approach 1. **Count Frequencies** using a hash map. 📊 2. **Bucket Sort** the numbers based on their frequencies. 🪣 3. **Collect** the top K frequent elements. 🎯 # ⏱️ Complexity - **Time Complexity:** $$O(N)$$ - **Space Complexity:** $$O(N)$$ # 💻 Code ```cpp [] class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { int n = nums.size(); unordered_map<int, int> map; vector<int> ans; for (int &x : nums) map[x]++; vector<vector<int>> arr(n + 1); for (auto [a, b] : map) arr[b].push_back(a); for (int i = n; i > 0; i--) { for (int &x : arr[i]) { if (ans.size() == k) return ans; ans.push_back(x); } } return ans; } }; ``` ```python [] class Solution: def topKFrequent(self, nums, k): from collections import Counter count = Counter(nums) bucket = [[] for _ in range(len(nums) + 1)] for num, freq in count.items(): bucket[freq].append(num) res = [] for i in range(len(nums), 0, -1): for num in bucket[i]: res.append(num) if len(res) == k: return res ``` ```java [] class Solution { public List<Integer> topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); List<Integer>[] bucket = new List[nums.length + 1]; for (int key : map.keySet()) { int freq = map.get(key); if (bucket[freq] == null) bucket[freq] = new ArrayList<>(); bucket[freq].add(key); } List<Integer> res = new ArrayList<>(); for (int i = nums.length; i > 0 && res.size() < k; i--) { if (bucket[i] != null) res.addAll(bucket[i]); } return res.subList(0, k); } } ``` <img src="https://assets.leetcode.com/users/images/7b864aef-f8a2-4d0b-a376-37cdcc64e38c_1735298989.3319144.jpeg" alt="upvote" width="150px"> # Connect with me on LinkedIn for more insights! 🌟 Link in bio
19
0
['Array', 'Hash Table', 'Divide and Conquer', 'Sorting', 'Heap (Priority Queue)', 'Bucket Sort', 'Python', 'C++', 'Java', 'Python3']
1
top-k-frequent-elements
Clear Java Quick Select O(n)
clear-java-quick-select-on-by-wsteg-ssle
\nclass Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n HashMap<Integer, Integer> map = new HashMap<>();\n for (int n : n
wsteg
NORMAL
2017-09-29T06:04:16.181000+00:00
2017-09-29T06:04:16.181000+00:00
1,518
false
```\nclass Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n HashMap<Integer, Integer> map = new HashMap<>();\n for (int n : nums) {\n map.put(n, map.getOrDefault(n, 0) + 1);\n }\n return quickSelect(map, new ArrayList<Integer>(map.keySet()), 0, map.size() - 1, k); \n }\n \n private List<Integer> quickSelect(HashMap<Integer, Integer> map, ArrayList<Integer> keys, int start, int end, int k) {\n int left = start, right = end;\n List<Integer> res = new ArrayList<>();\n\n while (left < right) {\n int pivot = partition(map, keys, left, right);\n if (pivot < k - 1) {\n left = pivot + 1;\n } else if (pivot > k - 1) {\n right = pivot - 1;\n } else {\n break;\n }\n }\n \n for (int i = 0; i < k; i++) {\n res.add(keys.get(i));\n }\n return res;\n }\n \n private int partition(HashMap<Integer, Integer> map, ArrayList<Integer> keys, int start, int end) {\n int left = start;\n int pivot = map.get(keys.get(start));\n for (int i = start + 1; i <= end; i++) {\n if (map.get(keys.get(i)) >= pivot) {\n Collections.swap(keys, i, ++left);\n }\n }\n Collections.swap(keys, start, left);\n return left;\n }\n}\n```
19
0
[]
1
top-k-frequent-elements
Powerful Heapmax and Hash Table
powerful-heapmax-and-hash-table-by-ganji-ymnv
\n# Heapmax and Hash Table\n\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n dic=Counter(nums)\n heapmax=[[-
GANJINAVEEN
NORMAL
2023-03-22T05:38:30.195972+00:00
2023-03-22T05:38:30.196024+00:00
4,488
false
\n# Heapmax and Hash Table\n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n dic=Counter(nums)\n heapmax=[[-freq,num] for num,freq in dic.items()]\n heapq.heapify(heapmax)\n list1=[]\n for i in range(k):\n poping=heapq.heappop(heapmax)\n list1.append(poping[1])\n return list1\n\n\n```\n# please upvote me it would encourage me alot\n
18
0
['Python3']
3
top-k-frequent-elements
C++|| Priority queue || Easy || Explained
c-priority-queue-easy-explained-by-angad-14uj
Hi everyone, today we will be solving Top K Frequent Elements.\nFor this question our simple approach will be to:\n\n1. Calculate frequency of the array element
angad_kochhar
NORMAL
2022-04-09T08:05:50.581172+00:00
2022-04-09T08:14:15.607199+00:00
3,910
false
#### Hi everyone, today we will be solving **Top K Frequent Elements.**\nFor this question our simple approach will be to:\n\n1. Calculate frequency of the array elements using unordered_map.\n2. Creating a pair of each distinct element of the array nums with their frequency and pushing it in a max heap with the format as <frequency, nums value>.(This will sort our elements based on maximum frequency such that we get the maximum occuring element at the top)\n3. Pop K top elements from our max heap and push it into our vector which is our ans and is returned.\n\nCode is attached below:\n\n**C++:**\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int>m;\n for(int i=0;i<nums.size();i++){\n m[nums[i]]++; //calculating frequency\n }\n unordered_map<int,int>::iterator it=m.begin();\n priority_queue<pair<int,int>>pq;\n for(;it!=m.end();it++){\n pq.push(make_pair(it->second,it->first)); //pushing pair of <frequency,distinct element of nums array> so that we get most occuring element on top\n }\n vector<int>ans;\n int a=0;\n while(a<k){\n ans.push_back(pq.top().second);\n pq.pop(); //popping k top most elements, inserting in our answer vector and returning the answer.\n a++;\n }\n return ans;\n }\n};\n```
18
0
['C', 'Heap (Priority Queue)', 'C++']
4
top-k-frequent-elements
C simple solution
c-simple-solution-by-dreamsoso-cn4f
\n\nstruct hashtable\n{\n int value;\n int cnt;\n};\n\n\n\nint cmp(const void *a, const void *b)\n{\n return *(const int *)a - *(const int *)b;\n}\n\ni
dreamsoso
NORMAL
2019-03-05T16:15:45.122538+00:00
2019-03-05T16:15:45.122581+00:00
1,915
false
```\n\nstruct hashtable\n{\n int value;\n int cnt;\n};\n\n\n\nint cmp(const void *a, const void *b)\n{\n return *(const int *)a - *(const int *)b;\n}\n\nint cmph(const void *a, const void *b)\n{\n return ((struct hashtable *)b)->cnt - ((struct hashtable *)a)->cnt;\n}\n\nint* topKFrequent(int* nums, int size, int k, int* returnSize) {\n if(k == 0 || size == 0){\n *returnSize = k;\n return 0;\n }\n if (size < k){\n *returnSize = 0;\n return 0;\n }\n if(size == k && k == 1){\n *returnSize = 1;\n return nums; \n }\n \n int *ans = calloc(k, sizeof(int));\n struct hashtable hash[size];\n memset(hash,0,sizeof(struct hashtable)*size);\n int i;\n int count=1;\n *returnSize = k;\n qsort(nums, size,sizeof(int),cmp);\n \n hash[0].value=nums[0];\n hash[0].cnt++;\n \n for (i=1;i<size;i++){\n if(hash[count-1].value == nums[i]){\n hash[count-1].cnt++;\n } else {\n count++;\n hash[count-1].value = nums[i];\n hash[count-1].cnt++;\n }\n }\n \n qsort(hash, count,sizeof(hash[0]),cmph);\n \n for(i=0;i<k;i++){\n ans[i] = hash[i].value;\n }\n \n return ans;\n \n}\n```
18
1
['C']
0
top-k-frequent-elements
✅C# LINQ One line solution
c-linq-one-line-solution-by-maxim_kurban-p16h
Code\n\npublic class Solution \n{\n public int[] TopKFrequent(int[] nums, int k) \n {\n return nums.GroupBy(num => num)\n .OrderByDescending
Maxim_Kurbanov
NORMAL
2023-05-08T23:29:47.971710+00:00
2023-05-08T23:29:47.971747+00:00
3,087
false
# Code\n```\npublic class Solution \n{\n public int[] TopKFrequent(int[] nums, int k) \n {\n return nums.GroupBy(num => num)\n .OrderByDescending(num => num.Count())\n .Take(k)\n .Select(c => c.Key)\n .ToArray();\n }\n}\n```
17
0
['C#']
6
top-k-frequent-elements
Bucket Sort Java with Explanation
bucket-sort-java-with-explanation-by-gra-c4jl
It is intuitive to map a value to its frequency. Then our problem becomes \'to sort map entries by their values\'.\nSince frequency is within the range [1, n] f
gracemeng
NORMAL
2018-10-08T16:43:06.213356+00:00
2018-10-16T04:12:36.566404+00:00
1,833
false
It is intuitive to map a value to its frequency. Then our problem becomes \'to sort map entries by their values\'.\nSince frequency is within the range [1, n] for n is the number of elements, we could apply the idea of **Bucket Sort**:\n- we divide frequencies into n + 1 buckets, in this way, the list in buckets[i] contains elements with the same frequency i\n- then we go through the buckets from tail to head until we collect k elements.\n****\n**Java**\n```\n public List<Integer> topKFrequent(int[] nums, int k) {\n int n = nums.length;\n List<Integer> result = new ArrayList<>();\n \n // Map elements to frequencies.\n Map<Integer, Integer> freqMap = buildFreqMap(nums);\n \n // Bucket sort on freqMap.\n List<Integer>[] bucket = buildBucketArray(n, freqMap);\n \n for (int i = nums.length; i >= 0 && k > 0; i--) {\n if (bucket[i] != null) {\n List<Integer> elements = bucket[i];\n int numToAdd = Math.min(k, elements.size());\n result.addAll(elements.subList(0, numToAdd));\n k -= numToAdd;\n }\n }\n \n return result;\n }\n \n private Map<Integer, Integer> buildFreqMap(int[] nums) {\n Map<Integer, Integer> freqMap = new HashMap<>();\n \n for (int num : nums) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n return freqMap;\n }\n \n private List<Integer>[] buildBucketArray(int n, Map<Integer, Integer> freqMap) {\n List<Integer>[] bucket = new ArrayList[n + 1];\n \n for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {\n int freq = entry.getValue();\n if (bucket[freq] == null)\n bucket[freq] = new ArrayList<>();\n bucket[freq].add(entry.getKey());\n }\n return bucket;\n }\n```\n**(\u4EBA \u2022\u0348\u1D17\u2022\u0348)** Thanks for voting!
17
0
[]
4
top-k-frequent-elements
5.1 (Approach 1) | O(n log n)✅ | Python & C++(Step by step explanation)✅
51-approach-1-on-log-n-python-cstep-by-s-vn0b
Intuition\n Describe your first thoughts on how to solve this problem. \nMy initial thoughts are to count the frequency of each element and then select the top
monster0Freason
NORMAL
2024-01-17T09:20:48.682702+00:00
2024-01-17T09:27:07.105486+00:00
4,443
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy initial thoughts are to count the frequency of each element and then select the top k frequent elements.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use a dictionary (lis) to count the frequency of each element in the input list (nums).\n2. Create an empty list (ans) to store the top k frequent elements.\n3. Iterate through nums and update the frequency count in the dictionary (lis).\n4. Sort the dictionary items based on frequency in descending order.\n5. Extract the top k frequent elements and append them to the ans list.\n6. Return the ans list.\n\n# Complexity\n- Time complexity:\n - The time complexity is O(n log n), where n is the length of the input list. This is due to the sorting step.\n- Space complexity:\n - The space complexity is O(n), where n is the number of unique elements in the input list. This is for the lis dictionary.\n \n# Code(Python)\n```python\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n # Step 1: Use a dictionary (lis) to count the frequency of each element in nums.\n lis = {} \n ans = [] \n for x in nums:\n if x in lis:\n lis[x] += 1\n else:\n lis[x] = 1\n \n # Step 2: Sort the dictionary items based on frequency in descending order.\n slis = sorted(lis.items(), key=lambda item: item[1], reverse=True)\n \n # Step 3: Extract the top k frequent elements and append them to the ans list.\n for i in range(k):\n ans.append(slis[i][0])\n \n return ans\n\n```\n\n# Code(C++)\n```c++\nclass Solution {\n static bool cmp(pair<int, int>& a, pair<int, int>& b) {\n return a.second > b.second;\n }\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n // Step 1: Use an unordered_map (mp) to count the frequency of each element in nums.\n unordered_map<int, int> mp;\n for (auto x : nums) {\n mp[x]++;\n }\n\n // Step 2: Create a vector of pairs (v) to store the elements and their frequencies.\n vector<pair<int, int>> v;\n for (auto x : mp) {\n v.push_back(pair{x.first, x.second});\n }\n\n // Step 3: Sort the vector based on frequencies in descending order.\n sort(v.begin(), v.end(), cmp);\n\n // Step 4: Create a vector (ans) to store the top k frequent elements.\n vector<int> ans;\n for (int i = 0; i < k; i++) {\n auto it = v.begin() + i;\n ans.push_back(it->first);\n }\n return ans;\n }\n};\n \n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/0161dd3b-ad9f-4cf6-8c43-49c2e670cc21_1699210823.334661.jpeg)\n\n
16
0
['C++', 'Python3']
0
top-k-frequent-elements
Python one-liner beats 98%
python-one-liner-beats-98-by-eduardocere-h97k
\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n return [x[0] for x in Counter(nums).most_common(k)]\n
eduardocereto
NORMAL
2022-04-09T00:18:39.798377+00:00
2022-04-09T02:55:24.296259+00:00
5,269
false
```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n return [x[0] for x in Counter(nums).most_common(k)]\n```
16
0
['Python', 'Python3']
6
top-k-frequent-elements
O(n) 32ms Java Solution - Bucket Sort
on-32ms-java-solution-bucket-sort-by-ofl-zv8m
public class Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n int n = nums.length;\n HashMap<Integer, Integer>
oflucas
NORMAL
2016-05-17T03:22:42+00:00
2016-05-17T03:22:42+00:00
4,356
false
public class Solution {\n public List<Integer> topKFrequent(int[] nums, int k) {\n int n = nums.length;\n HashMap<Integer, Integer> h = new HashMap();\n for (int i : nums)\n if (h.containsKey(i))\n h.put(i, h.get(i) + 1);\n else\n h.put(i, 1);\n \n List<Integer>[] fc = new ArrayList[n + 1];\n for (int i : h.keySet()) {\n int f = h.get(i); //System.out.println(f + " times of " + i);\n if (fc[f] == null) fc[f] = new ArrayList();\n fc[f].add(i);\n }\n \n List<Integer> ans = new ArrayList();\n for (int i = n, j = 0; k > 0; k--) {\n for (; fc[i] == null || j == fc[i].size(); j = 0, i--);\n ans.add(fc[i].get(j++));\n }\n \n return ans;\n }\n }
16
2
[]
1
top-k-frequent-elements
Golang solution O(n)
golang-solution-on-by-koroll-scss
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
koroll
NORMAL
2023-07-28T17:40:07.547132+00:00
2023-07-28T17:41:03.230636+00:00
2,414
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunc topKFrequent(nums []int, k int) []int {\n m := make(map[int]int)\n\n for _, val := range nums {\n m[val]++\n }\n\n bucket := make([][]int, len(nums)+1)\n\n for key, val := range m {\n bucket[val] = append(bucket[val], key)\n }\n\n ans := make([]int, 0, k)\n\n for i := len(bucket) - 1; i >=0; i-- {\n for _, val := range bucket[i] {\n if k > 0 {\n ans = append(ans, val)\n k--\n }\n }\n }\n\n return ans\n}\n```
15
0
['Go']
5
top-k-frequent-elements
C++ - Priority Queue Explained | | EASY
c-priority-queue-explained-easy-by-naman-3c2h
Intuition\nWe have to find the top "k" most occurring elements in the Priority Queue. \n\n# Approach\n- We will store the elements and their frequency in a Prio
Naman-Srivastav
NORMAL
2023-02-09T05:37:10.042147+00:00
2023-02-09T05:37:10.042181+00:00
2,903
false
# Intuition\nWe have to find the top "k" most occurring elements in the Priority Queue. \n\n# Approach\n- We will store the elements and their frequency in a Priority Queue(**Max Heap**).\n- We are using Priority Queue (**Max Heap**) because we will arrange the elements in descending order of their frequency,i.e.,most occurred element will be placed at the top of the Priority Queue.\n- Now the top "k" elements in the Priority Queue will be our answer.\n\n \n# Code\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n map<int,int> mp;\n for(auto it:nums)\n mp[it]++;\n vector<int> vec;\n priority_queue<pair<int,int>> pq;\n for(auto it:mp)\n pq.push({it.second,it.first});\n while(k--)\n {\n vec.push_back(pq.top().second);\n pq.pop();\n }\n return vec;\n }\n};\n```\n# **UPVOTE Solution**
15
0
['Heap (Priority Queue)', 'C++']
0
top-k-frequent-elements
Simple Java Solution | Using Priority Queue | Easy to understand
simple-java-solution-using-priority-queu-6u3h
\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n if( k == nums.length)\n return nums;\n\n int res[] = new int[k
shyamali341
NORMAL
2022-04-13T18:06:46.160583+00:00
2022-04-13T18:06:46.160622+00:00
1,908
false
```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n if( k == nums.length)\n return nums;\n\n int res[] = new int[k];\n HashMap<Integer, Integer> hm = new HashMap<>();\n\n for(int n: nums)\n hm.put(n, hm.getOrDefault(n, 0)+1);\n\n PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> hm.get(b) - hm.get(a));\n\n for(int i: hm.keySet())\n pq.offer(i);\n\n for(int i=0; i< k;i++)\n res[i] = pq.poll();\n\n return res;\n }\n}\n```
15
0
['Heap (Priority Queue)', 'Java']
2
top-k-frequent-elements
python dictionary and heap
python-dictionary-and-heap-by-jefferyzzy-ozr6
\nimport heapq\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n res = []\n dict = {}\n for num in nums
jefferyzzy
NORMAL
2019-12-10T00:16:48.340033+00:00
2019-12-10T00:19:21.135135+00:00
4,045
false
```\nimport heapq\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n res = []\n dict = {}\n for num in nums:\n if num not in dict:\n dict[num] = 1\n else:\n dict[num]+=1\n for key, val in dict.items():\n if len(res) < k:\n heapq.heappush(res, [val,key])\n else:\n heapq.heappushpop(res, [val,key])\n return [y for x, y in res]\n```
14
0
['Heap (Priority Queue)', 'Python', 'Python3']
6
top-k-frequent-elements
C# - BEST 2 SOLUTIONS (BUCKET SORT - PRIORITY QUEUE)⬆️
c-best-2-solutions-bucket-sort-priority-75x5m
Solutions\n Describe your approach to solving the problem. \nI\'m giving two solutions with different runtimes. Please tell me which one would you pick :) and w
Mossad
NORMAL
2023-08-23T05:01:05.154088+00:00
2023-08-23T05:05:12.111384+00:00
2,213
false
# Solutions\n<!-- Describe your approach to solving the problem. -->\n**I\'m giving two solutions with different runtimes. Please tell me which one would you pick :) and why ?**\n\n#### 1. Bucket Sort\n##### Complexity\n- Time complexity: $$O(n)$$\n- Space Complexity: $$O(n)$$\n##### Code\n```\npublic class Solution {\n public int[] TopKFrequent(int[] nums, int k) {\n // Step 1: Build the frequency map of elements in the nums array\n Dictionary<int, int> freqMap = new Dictionary<int, int>();\n foreach (var num in nums) {\n if (freqMap.ContainsKey(num))\n freqMap[num]++;\n else\n freqMap[num] = 1;\n }\n\n // Step 2: Prepare a list of lists to store elements with the same frequency\n List<int>[] buckets = new List<int>[nums.Length + 1];\n foreach (var num in freqMap.Keys) {\n int freq = freqMap[num];\n if (buckets[freq] == null)\n buckets[freq] = new List<int>();\n buckets[freq].Add(num);\n }\n\n // Step 3: Build the result array from buckets in descending order of frequency\n List<int> result = new List<int>();\n for (int i = buckets.Length - 1; i >= 0 && result.Count < k; i--) {\n if (buckets[i] != null)\n result.AddRange(buckets[i]);\n }\n\n // Step 4: Convert the result list to an array and return\n return result.ToArray();\n }\n}\n```\n---\n#### 2. Priority Queue (Heap)\n##### Complexity\n- Time complexity: $$O(n * logk)$$\n- Space Complexity: $$O(n + k)$$\n##### Code\n```\npublic class Solution {\n public int[] TopKFrequent(int[] nums, int k) {\n Dictionary<int, int> freqMap = new();\n for(int i = 0; i < nums.Length; i++) {\n if (freqMap.ContainsKey(nums[i]))\n freqMap[nums[i]]++;\n else\n freqMap[nums[i]] = 1;\n }\n\n PriorityQueue<int, int> pq = new();\n foreach(var key in freqMap.Keys) {\n pq.Enqueue(key, freqMap[key]);\n if (pq.Count > k)\n pq.Dequeue();\n }\n\n int[] res = new int[k];\n int j = k;\n\n while (pq.Count > 0)\n res[--j] = pq.Dequeue();\n\n return res;\n }\n}\n```
13
0
['Heap (Priority Queue)', 'Bucket Sort', 'C#']
4
top-k-frequent-elements
HashMap✅|| PriorityQueue👍|| Simple Approach🔥|| Easy to Understand🤩
hashmap-priorityqueue-simple-approach-ea-g3de
Intuition\n Describe your first thoughts on how to solve this problem. \nBeginner friendly approach to solve this questions by \n- Putting the frequency of all
kartikeymish
NORMAL
2023-05-22T06:01:25.967878+00:00
2023-05-22T06:01:52.461638+00:00
8,286
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBeginner friendly approach to solve this questions by \n- Putting the frequency of all elements in an hash map ,then\n- Putting the keys in a priority queue on the basis of there frequency values, and\n- Getting the top k elements in an aray.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSteps invlolved : \n\n1. Creating the frequncy table: \n - using the `put()` to give values input of the integer and its occurence by `getOrDefault(n,0)+1` i.e. of the key is present then its occurence else give the default value 0.\n```Java[]\n Map<Integer,Integer> map = new HashMap();\n for(int n : nums){\n map.put(n,map.getOrDefault(n,0) + 1);\n }\n```\n2. Adding the keys of HashMap to the PriorityQueue by creating a Maxheap using a mlamda function. \n```\nPriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->map.get(b) map.get(a));\npq.addAll(map.keySet());\n```\n3. Putting the top k values in the output array. using the `poll()` to get the top value from the pq and removing it. \n```\nint[] res = new int[k];\n for(int i = 0;i<k;i++){\n res[i] = pq.poll();\n }\n return res;\n```\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n \n // Creating a Frequency Table\n Map<Integer,Integer> map = new HashMap();\n for(int n : nums){\n map.put(n,map.getOrDefault(n,0) + 1);\n }\n // Putting values in priority queue \n PriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->map.get(b) - map.get(a));\n pq.addAll(map.keySet());\n\n // putting the top k values in array\n int[] res = new int[k];\n for(int i = 0;i<k;i++){\n res[i] = pq.poll();\n }\n return res;\n }\n}\n```
13
0
['Array', 'Hash Table', 'Divide and Conquer', 'Heap (Priority Queue)', 'Java']
3
top-k-frequent-elements
Better Time/Space performance than Top Ranked Python Solution
better-timespace-performance-than-top-ra-85ah
This solution, which uses a bucket sort, improves on one of the top ranked solutions (here).\n\nNaive bucket sort looks something like this:\npython\nclass Solu
constantstranger
NORMAL
2022-04-09T13:35:00.091619+00:00
2022-04-09T22:22:22.590550+00:00
794
false
This solution, which uses a bucket sort, improves on one of the top ranked solutions ([here](https://leetcode.com/problems/top-k-frequent-elements/discuss/740374/Python-5-lines-O(n)-buckets-solution-explained.)).\n\nNaive bucket sort looks something like this:\n```python\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n from collections import Counter\n ranked = [[] for _ in range(len(nums) + 1)]\n c = Counter(nums)\n for key, val in c.items():\n ranked[val].append(key)\n return list(chain(*ranked))[len(c) - k:]\n```\nWhat it\'s doing is this:\n* Because frequencies can theoretically be anywhere from 1 to len(nums), create an array of arrays called `ranked` to take any frequency up to a value of len(nums) as an index.\n* Use a Counter object `c` to calculate frequencies of input array elements.\n* For any actual frequency values that occur in `c`, append to that bucket in `ranked` every element from the input array with a matching frequency.\n* Now chain together all the buckets in `ranked` (including a lot of empty ones) so that the unique elements of the input array are sorted by frequency, and select those with the top k frequencies.\n\nBucket sort is a great approach to finding the top k frequent elements in an array, and it clearly satisfies the problem\'s follow up challenge: "Your algorithm\'s time complexity must be better than O(n log n), where n is the array\'s size."\n\nHowever, we can easily do a lot better than naive bucket sort and improve on its average time and space performance with these 3 steps:\n* Create a dictionary `freqs` that maps each count value in `c` to a bucket index in a sparse bucket array, `ranked`. Order the buckets in a way that ensures the highest frequency elements are stored in `ranked[0]`, the second highest frequency elements in `ranked[1]`, etc.\n* Create `ranked` sparsely with one list for each actual frequency present in `freqs`. This means we never need to allocate space for a lot of empty lists that we will never use.\n* Walk through our buckets in `ranked` (ordered from highest to lowest frequency) and take the first k elements, without bothering to chain together lists of elements below the top k frequencies.\n```python\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n from collections import Counter\n c = Counter(nums)\n freqs = {v : 0 for v in c.values()}\n i = len(freqs) - 1\n for freq in range(len(nums) + 1):\n if freq in freqs:\n freqs[freq], i = i, i - 1\n ranked = [[] for _ in range(len(freqs))]\n for elem, freq in c.items():\n ranked[freqs[freq]].append(elem)\n i, res = 0, [0] * k\n while k:\n j = min(k, len(ranked[i]))\n for m in range(j):\n res[m + len(res) - k] = ranked[i][m]\n i, k = i + 1, k - j\n return res\n```\nLet\'s see how this compares to naive bucket sort.\n\nThe problem constraints have:\n```\n1 <= nums.length <= 10^5\nk is in the range [1, the number of unique elements in the array]\n```\nAs an example, suppose we have k of 10 and nums with length 100,000 containing 100 unique values with frequencies averaging 1,000 each.\n\nIn the naive approach, we initialize our bucket array to be a list of 100,000 empty lists, of which we actually populate only 100 (or 0.1% of the total number of buckets). We then chain together 100,000 lists (at least 99,900 of which are empty) containing a total of 100 unique values, take the top 10 values by frequency and discard the remaining 90 values.\n\nIn the improved approach, we initalize our frequency dict and our bucket array to each have a length of 100. We then read off the first 10 elements from the first one or more buckets (10 at most) and copy them to a result array of length 10.\n\nHopefully this gives a clear picture of the difference between the improved and naive solutions.
13
0
['Python']
4
top-k-frequent-elements
All solutions discussed || O(n)
all-solutions-discussed-on-by-____champi-9nxc
Priority Queues : O(nlogk)\n Algorithm:\n1. Create a map of elements and their frequencies.\n2. Make a min-priority queues,.\n3. Push k pairs into the queue.
____CHAMPION99
NORMAL
2022-01-17T16:27:37.154502+00:00
2022-01-17T16:27:37.154550+00:00
1,087
false
**Priority Queues : O(nlogk)**\n Algorithm:\n1. Create a map of elements and their frequencies.\n2. Make a min-priority queues,.\n3. Push k pairs into the queue.\n4. After inserting k pairs, insert a new pair and pop the minimum frequency pair to maintain the size of q exactly k.\n5. Now pop the maximum frequency k values and push the pair elements in the answer vector.\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int>map;\n for(int i=0;i<nums.size();i++)\n {\n map[nums[i]]++;\n }\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;\n int count=1;\n for(auto it:map)\n {\n pq.push({it.second,it.first});\n if(count>k)\n {\n pq.pop();\n }\n count++;\n \n }\n vector<int>ans;\n while(!pq.empty())\n {\n ans.push_back(pq.top().second);\n pq.pop();\n }\n return ans;\n \n }\n};\n```\n2. **Stl** way to implement priority_queues internally in **partial_sort : O(nlogk)**\nStl function partial_sort internally uses priority queues to sort the array till the middle iterator passed.\n`partial_sort( begin, middle ,end)` sorts the vector in range `[begin, middle)`.\n```\nclass compare\n{\n public:\n bool operator()(pair<int,int>const&a,pair<int,int>const&b)\n const\n {\n return a.second>b.second; \n }\n \n};\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int>map;\n for(int i=0;i<nums.size();i++)\n {\n map[nums[i]]++;\n }\n vector<pair<int,int>>fre(map.begin(),map.end());\n partial_sort(fre.begin(),fre.begin()+k,fre.end(),compare());\n vector<int>ans;\n for(int i=0;i<k;i++)\n {\n ans.push_back(fre[i].first);\n }\n return ans;\n \n \n }\n};\n```\n**Bucket Sort: O(n)**\nAlgorithm:\n1. Taking advantage of the range of frequencies which are belong to [1,n] in the frequency map.\n2. First make a frequency map, now create a vector of vector of pairs called buckets, the index of the bucket +1 is equal to frequency of that pair inserted.\n3. Now combine all buckets to form the sorted pairs according to their frequencies.\n4. return the last k elements.\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int>map;\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n map[nums[i]]++;\n }\n vector<vector<int>>buckets(n);\n for(auto it=map.begin();it!=map.end();it++)\n {\n buckets[it->second-1].push_back(it->first);\n }\n vector<int>sorted;\n for(int i=0;i<n;i++)\n {\n sorted.insert(sorted.end(),buckets[i].begin(),buckets[i].end());\n }\n vector<int>ans(sorted.rbegin(),sorted.rbegin()+k);\n return ans;\n \n \n \n \n }\n};\n```\n**Quick Selection : O(n)**\nAlgorithm:\n1. Here first make a frequency map.\n2. Now we need only the largest frequency k elements, so if in ascending order, we need all numbers at and beyond index n-k.\n3. We will select a pivot ,now partition the frequencies <=pivot_frequency in the left and frequency>pivot_frequency at the right.\n4. If the pivot is at **n-kth** position then just return the right part of the elements,\n5. else `if pivot_index < n-k, quick_select ( start, pivot_index-1);`\n6. else `quick_select( pivot_index+1, end)`.\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int>map;\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n map[nums[i]]++;\n }\n vector<pair<int,int>>unique(map.begin(),map.end());\n quick_select(unique,0,unique.size()-1,unique.size()-k);\n vector<int>ans;\n for(int i=unique.size()-k;i<unique.size();i++)\n {\n ans.push_back(unique[i].first);\n }\n return ans;\n \n \n }\n private:\n void quick_select(vector<pair<int,int>>&unique,int start,int end,int k)\n {\n int pivot=unique[end].second;\n int j=start;\n for(int i=start;i<end;i++)\n {\n if(unique[i].second<=pivot)\n {\n swap(unique[i],unique[j]);\n j++;\n }\n }\n swap(unique[end],unique[j]);\n if(j==k)\n return;\n else\n if(j>k)\n return quick_select(unique,start,j-1,k);\n else\n return quick_select(unique,j+1,end,k);\n }\n};\n```\n5. **Stl** way to implement quick selection through **nth_selection: O(n)**\nStl has a function to implement quick selection\n`nth_selection( begin, pivot_index, end)`\n```\nclass compare\n{\n public:\n bool operator()(pair<int,int>const&a,pair<int,int>const&b)\n const\n {\n return a.second<b.second;\n \n }\n \n \n};\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int>map;\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n map[nums[i]]++;\n }\n int unique=map.size();\n vector<pair<int,int>>v(map.begin(),map.end());\n nth_element(v.begin(),v.begin()+unique-k,v.end(),compare());\n vector<int>ans;\n for(int i=unique-k;i<unique;i++)\n {\n ans.push_back(v[i].first);\n \n }\n return ans;\n }\n};\n```\n\n**Please upvote if you like it!!**\n
13
0
['C', 'Sorting', 'Heap (Priority Queue)', 'C++']
0
top-k-frequent-elements
C++ 20ms solution using Map and Heap
c-20ms-solution-using-map-and-heap-by-se-eu2a
\n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n int n=nums.size();\n unordered_map<int,int> m;\n
sethlakshya98
NORMAL
2020-04-08T00:05:03.017197+00:00
2020-04-08T00:07:23.910799+00:00
1,739
false
```\n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n int n=nums.size();\n unordered_map<int,int> m;\n for(int i=0;i<n;i++){\n m[nums[i]]++;\n }\n priority_queue<pair<int,int>> pq; //Fisrt element stores frequency and second element value\n\t\t//As we have not use any compare function max heap will sort according to first element of pair\n unordered_map<int,int>::iterator itr;\n for(itr=m.begin();itr!=m.end();itr++){\n pq.push(make_pair(itr->second,itr->first));\n }\n vector<int> ans(k);\n for(int i=0;i<k;i++){\n ans[i]=pq.top().second;\n pq.pop();\n }\n return ans;\n }\n};\n\n```
13
0
['C', 'Heap (Priority Queue)']
0
top-k-frequent-elements
Clean JavaScript solution
clean-javascript-solution-by-hongbo-miao-u6lu
\nconst topKFrequent = (nums, k) => {\n const map = {};\n for (const n of nums) {\n if (map[n] == null) map[n] = 0;\n map[n]++;\n }\n\n const arr = []
hongbo-miao
NORMAL
2019-10-01T00:52:04.440668+00:00
2020-09-02T15:48:13.803481+00:00
3,495
false
```\nconst topKFrequent = (nums, k) => {\n const map = {};\n for (const n of nums) {\n if (map[n] == null) map[n] = 0;\n map[n]++;\n }\n\n const arr = [];\n for (const n in map) {\n arr.push({ n, count: map[n] });\n }\n\n return arr\n .sort((a, b) => b.count - a.count)\n .slice(0, k)\n .map(a => Number(a.n));\n};\n```\n
13
4
['JavaScript']
5
top-k-frequent-elements
Python solution with detailed explanation
python-solution-with-detailed-explanatio-ckv2
Solution\n\nTop K Frequent Elements https://leetcode.com/problems/top-k-frequent-elements/?tab=Description\n\nHeap: klog(N)\n Klog(N) - Create a frequency map
gabbu
NORMAL
2017-02-23T01:46:17.780000+00:00
2018-09-17T17:48:05.648171+00:00
3,791
false
**Solution**\n\n**Top K Frequent Elements** https://leetcode.com/problems/top-k-frequent-elements/?tab=Description\n\n**Heap: klog(N)**\n* Klog(N) - Create a frequency map and then add every tuple (frequency, item) to a max heap. Then extract the top k elements.\n\n```\nimport heapq\nfrom collections import Counter, defaultdict\nclass Solution(object):\n def topKFrequent(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n """\n heap = [(-1*v1, k1) for k1,v1 in Counter(nums).items()]\n heapq.heapify(heap)\n result = []\n for i in range(k):\n result.append(heapq.heappop(heap)[1])\n return result\n```\n\n**Heap: Nlog(k)**\n* Create a frequency map.\n* Add k tuples (frequency, item) to min-heap.\n* Iterate from k+1st tuple to Nth tuple. If the tuple frequency is more than top of heap, pop from heap and add the tuple. \n* Finally the heap will have k largest frequency numbers\n\n**Bucket Sort**\n```\nfrom collections import Counter, defaultdict \nclass Solution(object):\n def topKFrequent(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n """\n freq, result = Counter(nums), []\n inverse_freq = defaultdict(list)\n for k1,v1 in freq.items():\n inverse_freq[v1].append(k1)\n for x in range(len(nums), 0, -1):\n if x in inverse_freq:\n result.extend(inverse_freq[x])\n if len(result) >= k:\n break\n return result[:k]\n```
13
0
[]
4
top-k-frequent-elements
Simple Solution || HashMap || Beginner Friendly || With proper explanation ||
simple-solution-hashmap-beginner-friendl-rlna
Intuition\n Describe your first thoughts on how to solve this problem. \nI have this problem using hashmap to clear my concept of hashmap and array.\n\n# Approa
Vaibhav_Shelke1
NORMAL
2024-02-05T16:06:47.969069+00:00
2024-02-05T16:06:47.969097+00:00
4,646
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI have this problem using hashmap to clear my concept of hashmap and array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI hav solve this problem using Following Steps:\n\n1] I have created Hashmap--> map. which is taking key as integer and value will also be integer.\nkey-->element of array.\nvalue--> how many time they have occer.\n\n2] Then in i have use loop to put array value in map and increase value by 1 if it occer in array again.\n\n3]Create a list containing unique elements from the frequency map (keys of the map).\n\n4] Sorts the list of unique elements based on their frequencies in descending order.In this all the element that has high frequency in the starting of list.\n\n5] we have to return array so we declear res[] array to return result.\n\n6]Fill the k element of shorted element in list.\n\n7] return the result.\n\n this is simple explanation of my program.\n\n\n\n\n\n\n\nIn where I can decrease time and space please comment help me in learning and also please upvote this program.\n\n# Code\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer,Integer>map=new HashMap<>();\n for(int i:nums)\n {\n if(map.containsKey(i))\n {\n map.put(i,map.get(i)+1);\n }\n else{\n map.put(i,1);\n }\n }\n List<Integer>list=new ArrayList<>(map.keySet());\n list.sort((a, b) -> map.get(b) - map.get(a));\n int res[] = new int[k];\n for (int i = 0; i < k; ++i)\n res[i] = list.get(i);\n return res;\n\n }\n}\n```
12
0
['Hash Table', 'Sorting', 'Java']
4
top-k-frequent-elements
Very Simple Beginner Friendly Thoroughly Explained C++ Solution
very-simple-beginner-friendly-thoroughly-4bkx
Intuition\nWe\'ll be using bucket sort, bucketing the elements to their frequency then using backwards iteration to find the Kth most frequent\n Describe your f
dorj910
NORMAL
2023-08-08T20:21:27.498693+00:00
2023-08-08T20:21:27.498711+00:00
1,213
false
# Intuition\nWe\'ll be using bucket sort, bucketing the elements to their frequency then using backwards iteration to find the Kth most frequent\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach \nFirst: Create our return vector, then create a hash map with integer key and value pairs. The key will be the number in the array, and the value will be the number of occurences\n\nSecond: Iterate through the input array and count the number of occurences for each integer for [1,1,1,2,2,3] we would assign the value "3" to the key "1" because "1" appears 3 times and repeat the process for every integer\n\nThird: create an array of arrays, this is the bucket that will store the number of occurences.\n\nFourth: Iterate through the dictionary. In order to iterate through a dictionary we use for (auto (variable): dict) and we use the occurences as the index, and bucket the number based off the number of occurences\n\nFifth: Iterate backwards through the buckets, knowing that the first element we hit is the highest frequency, second element is the second highest frequency... then we keep going until the Kth element and we stop.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: Linear time O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) because we\'re using dictionary\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int,int> dict;\n vector<int> res; //return vector\n for (int i: nums) \n {\n dict[i]++; //count occurences of elements\n }\n vector<vector<int>>bucket(nums.size()+1); //bucket for the elements\n for (auto it: dict) //iterate through dictionary\n {\n bucket[it.second].push_back(it.first); //dictionary value will be assigned to key\n //the element is bucketed to its occurences\n }\n //iterate backwards, first element is most frequent, second element second most frequent\n for (int i = nums.size(); i > 0; i--)\n {\n if (k==0) return res;//stop at the kth element\n for (int j = 0; j < bucket[i].size(); j++)\n {\n res.push_back(bucket[i][j]);\n k--;\n }\n }\n return res;\n }\n};\n```
12
0
['Hash Table', 'C++']
4
top-k-frequent-elements
solution code in java
solution-code-in-java-by-ahmedna126-z1ri
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ahmedna126
NORMAL
2023-05-22T13:55:05.051356+00:00
2023-11-07T11:46:13.171839+00:00
9,789
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n int [] output = new int[k];\n int n = nums.length;\n \n HashMap <Integer , Integer> emp = new HashMap<>();\n \n boolean visited[] = new boolean[n];\n \n Arrays.fill(visited, false);\n\n for (int i = 0; i < n; i++) {\n\n if (visited[i] == true)\n continue;\n \n int count = 1;\n for (int j = i + 1; j < n; j++) {\n if (nums[i] == nums[j]) {\n visited[j] = true;\n count++;\n }\n }\n \n emp.put(nums[i], count);\n \n }\n \n \n List<Map.Entry<Integer, Integer>> list = new LinkedList<>(emp.entrySet());\n Collections.sort(list, Map.Entry.comparingByValue(Comparator.reverseOrder()));\n \n List<Integer> topKKeys = list.stream().map(Map.Entry::getKey).limit(k).collect(Collectors.toList());\n \n for (int i = 0; i < k; i++) {\n output[i] = topKKeys.get(i);\n }\n \n \n return output;\n }\n}\n```\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository](https://github.com/ahmedna126/java_leetcode_challenges)\n\n![abcd1.jpeg](https://assets.leetcode.com/users/images/11bdfed1-f534-4dfe-9c1b-a5bcb11958af_1699357569.5456002.jpeg)\n
12
0
['Java']
0
top-k-frequent-elements
Java Solution | HashMap | PriorityQueue
java-solution-hashmap-priorityqueue-by-p-wjz8
\nclass Solution {\n public class Pair implements Comparable<Pair>\n {\n int num;\n int count;\n public Pair(int num,int count)\n
pavneet5013
NORMAL
2021-12-22T15:00:02.451814+00:00
2021-12-22T15:00:02.451847+00:00
1,805
false
```\nclass Solution {\n public class Pair implements Comparable<Pair>\n {\n int num;\n int count;\n public Pair(int num,int count)\n {\n this.num=num;\n this.count=count;\n }\n public int compareTo(Pair o)\n {\n return this.count - o.count;\n }\n \n }\n public int[] topKFrequent(int[] nums, int k) {\n HashMap<Integer,Integer> hm=new HashMap<>();\n for(int i=0;i<nums.length;i++)\n {\n if(hm.containsKey(nums[i]))\n {\n int of=hm.get(nums[i]);\n int nf=of+1;\n hm.put(nums[i],nf);\n }\n else\n {\n hm.put(nums[i],1);\n }\n }\n PriorityQueue<Pair> pq=new PriorityQueue<>();\n for(int key:hm.keySet())\n {\n Pair p=new Pair(key,hm.get(key));\n if(pq.size()<k)\n {\n pq.add(p);\n }\n else\n {\n Pair curr=pq.peek();\n if(p.count>curr.count)\n {\n pq.remove(curr);\n pq.add(p);\n \n }\n }\n }\n int[] res=new int[k];\n for(int i=0;i<k;i++)\n {\n res[i]=pq.remove().num;\n }\n return res;\n }\n}\n```
12
0
['Heap (Priority Queue)', 'Java']
1
top-k-frequent-elements
JavaScript Clean O(N) - Quick-Select
javascript-clean-on-quick-select-by-cont-7fpl
I\'ve explained the quick select approach in detail here ==> https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/664455/JavaScript-Iterative-Q
control_the_narrative
NORMAL
2020-07-31T17:11:25.017007+00:00
2020-07-31T17:13:25.395054+00:00
3,036
false
I\'ve explained the quick select approach in detail here ==> https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/664455/JavaScript-Iterative-Quick-Select-O(N)-Heavily-Commented\n```javascript\nvar topKFrequent = function(nums, k) {\n const map = new Map();\n for(let n of nums) map.set(n, (map.get(n) || 0) + 1);\n const keys = [...map.keys()], finalIdx = keys.length - k;\n let start = 0, end = keys.length-1;\n \n while(start <= end) {\n const pivot = Math.floor(Math.random() * (end - start + 1)) + start;\n const pivotIdx = pivotHelper(pivot, start, end);\n \n if(pivotIdx === finalIdx) return keys.slice(finalIdx);\n if(pivotIdx < finalIdx) start = pivotIdx + 1;\n else end = pivotIdx - 1;\n }\n \n function pivotHelper(pivot, start, end) {\n // move pivot away to the end\n swap(pivot, end);\n let swapIdx = start;\n \n for(let i = start; i < end; i++) {\n if(map.get(keys[i]) < map.get(keys[end])) {\n swap(swapIdx, i); swapIdx++;\n }\n }\n swap(swapIdx, end);\n return swapIdx;\n }\n \n function swap(i, j) {\n [keys[i], keys[j]] = [keys[j], keys[i]];\n }\n};\n```
12
1
['JavaScript']
0
top-k-frequent-elements
Java three solutions (map, priority queue)
java-three-solutions-map-priority-queue-n31du
1.map + sort: O(n) + O(nlogn)\n\njava\npublic List<Integer> topKFrequent(int[] nums, int k) {\n // boundary check\n if (nums == null || nums.length == 0 |
sarishinohara
NORMAL
2019-06-25T21:40:48.009568+00:00
2019-06-25T21:40:48.009634+00:00
925
false
1.map + sort: O(n) + O(nlogn)\n\n```java\npublic List<Integer> topKFrequent(int[] nums, int k) {\n // boundary check\n if (nums == null || nums.length == 0 || k <= 0) return null;\n \n // put elements into map\n HashMap<Integer, Integer> map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);\n }\n\n // boundary check again\n if (k > map.size()) return null;\n \n // put entries into a list\n List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(map.entrySet());\n \n // sort list by comparator\n entries.sort(Map.Entry.<Integer, Integer>comparingByValue().reversed());\n \n // return result\n List<Integer> res = new ArrayList<>();\n for (int i = 0; i < k; i++) {\n res.add((int) entries.get(i).getKey());\n }\n return res;\n}\n```\n\n2.priority queue(min heap): O(nlogk), used when k much less than n\n\n```java\npublic List<Integer> topKFrequent(int[] nums, int k) {\n if (nums == null || nums.length == 0 || k <= 0) return null;\n \n // count frequencies by map, use foreach\n Map<Integer, Integer> map = new HashMap<>();\n for (int i : nums) {\n map.put(i, map.getOrDefault(i, 0) + 1);\n }\n\n // boundary check again\n if (k > map.size()) return null;\n \n // create a priority queue(min heap with regard to map.values())\n PriorityQueue<Map.Entry<Integer, Integer>> q = \n new PriorityQueue<>(Map.Entry.comparingByValue());\n for (Map.Entry e : map.entrySet()) {\n q.offer(e);\n if (q.size() > k) \n q.poll();\n }\n \n // create result list\n List<Integer> res = new ArrayList<>();\n for (Map.Entry e : q) {\n res.add((int)e.getKey());\n }\n return res;\n}\n```\n\n3.priority queue(max heap): O(nlog(n - k)), used when k is almost equal to n\n\n```java\npublic List<Integer> topKFrequent(int[] nums, int k) {\n if (nums == null || nums.length == 0 || k <= 0) return null;\n \n // count frequencies by map\n Map<Integer, Integer> map = new HashMap<>();\n for (int i : nums) {\n map.put(i, map.getOrDefault(i, 0) + 1);\n }\n \n // boundary check again\n if (k > map.size()) return null;\n \n // create result list\n List<Integer> res = new ArrayList<>();\n \n // create a priority queue(max heap)\n PriorityQueue<Map.Entry<Integer, Integer>> q = \n new PriorityQueue<>(Map.Entry.<Integer, Integer>comparingByValue().reversed()); // n - k\n for (Map.Entry e : map.entrySet()) {\n q.offer(e);\n if (q.size() > map.size() - k) // get elements excluded from max heap \n res.add((int)q.poll().getKey());\n }\n return res;\n}\n```
12
0
['Heap (Priority Queue)']
1
top-k-frequent-elements
36ms neat c++ solution using stl heap tool
36ms-neat-c-solution-using-stl-heap-tool-0m67
vector<int> topKFrequent(vector<int>& nums, int k) {\n if (nums.empty()) return {};\n unordered_map<int, int> m;\n for (auto &n
vesion
NORMAL
2016-05-29T13:57:38+00:00
2016-05-29T13:57:38+00:00
2,160
false
vector<int> topKFrequent(vector<int>& nums, int k) {\n if (nums.empty()) return {};\n unordered_map<int, int> m;\n for (auto &n : nums) m[n]++;\n \n vector<pair<int, int>> heap;\n for (auto &i : m) heap.push_back({i.second, i.first});\n \n vector<int> result; \n make_heap(heap.begin(), heap.end());\n while (k--) {\n result.push_back(heap.front().second);\n pop_heap(heap.begin(), heap.end());\n heap.pop_back();\n }\n return result;\n }
12
0
['C++']
2
top-k-frequent-elements
One-Line Java O(nlogn) Solution Using Stream
one-line-java-onlogn-solution-using-stre-y9hw
Intuition\n 1. \nThis solution focuses on the application of the Java Stream API.\n\n# Approach\n Describe your approach to solving the problem. \nIt first uses
HMWCS
NORMAL
2023-01-20T04:26:28.477066+00:00
2023-01-21T01:18:24.280105+00:00
3,411
false
# Intuition\n<!-- 1. -->\nThis solution focuses on the application of the Java Stream API.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIt first uses the Arrays.stream() method to convert the "nums" array into a stream of integers, then uses the boxed() method to convert the integers into Integers, and then uses the collect() method with Collectors.groupingBy() to group the Integers by their value and count the occurrences of each value using Collectors.summingInt().\n\nIt then uses the entrySet() method to convert the resulting map into a Set of map entries, and sorts the entries by their values in descending order using Map.Entry.comparingByValue(). Finally, it uses the limit() method to return only the first "k" elements of the sorted set, maps the entries to their keys using the mapToInt() method, and then converts the resulting IntStream to an array using the toArray() method.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n return nums.length == k ? nums : \n Arrays.stream(nums).boxed().collect(\n Collectors.groupingBy(e -> e, Collectors.summingInt(e -> 1))\n )\n .entrySet().stream().sorted(\n Map.Entry.comparingByValue((a, b) -> Integer.compare(b, a))\n )\n .limit(k).mapToInt(e -> e.getKey()).toArray();\n }\n}\n```
11
0
['Hash Table', 'Sorting', 'Java']
0
top-k-frequent-elements
✔Python || Faster than 99.80% || 2 line easy solution using hashmap
python-faster-than-9980-2-line-easy-solu-zscv
\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n num=Counter(nums)\n return sorted(num, key = num.get, rever
kaii-23
NORMAL
2022-09-02T14:34:56.216819+00:00
2022-09-02T14:34:56.216865+00:00
2,333
false
```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n num=Counter(nums)\n return sorted(num, key = num.get, reverse=True)[:k]\n```
11
1
['Python']
6
top-k-frequent-elements
C++ 95% Faster solution using unordered_map and comparator
c-95-faster-solution-using-unordered_map-p6ju
Please do upvote if you like my solution/approach.\n\n\nclass Solution {\nprivate:\n\t// comparator function for sorting the vector of pairs in\n\t// non-increa
travanj05
NORMAL
2022-04-09T09:08:01.265488+00:00
2022-11-13T05:46:55.323493+00:00
710
false
Please do **upvote** if you like my solution/approach.\n\n```\nclass Solution {\nprivate:\n\t// comparator function for sorting the vector of pairs in\n\t// non-increasing order of second elements\n\tstatic bool compare(const pair<int, int> &a, const pair<int, int> &b) {\n\t\treturn a.second > b.second;\n\t}\npublic:\n\tvector<int> topKFrequent(vector<int> &nums, int k) {\n\t\tunordered_map<int, int> mp;\n\t\tfor (int &num : nums) mp[num]++; // stores the frequency of each num from the nums vector\n\t\tvector<pair<int, int>> v(mp.begin(), mp.end());\n\t\tsort(v.begin(), v.end(), compare); // sorts the vector of pairs in non-increasing order of second elements\n\t\tnums.clear();\n\t\tfor (int i = 0; i < k; i++) {\n\t\t\tnums.push_back(v[i].first); // adds the first k most appeared elements in an empty vector\n\t\t}\n\t\treturn nums;\n\t}\n};\n```\n\n
11
0
['C', 'Sorting']
2
top-k-frequent-elements
TreeMap Java with Explanations
treemap-java-with-explanations-by-gracem-733c
Logical Thought\nIt is intuitive to map a unique element value to its frequency.\nSince we are asked to get top K frequent, we ought to sort values of the mappi
gracemeng
NORMAL
2018-09-07T20:23:17.838123+00:00
2018-09-09T13:02:34.067279+00:00
935
false
**Logical Thought**\nIt is intuitive to map a unique element value to its frequency.\nSince we are asked to get top K frequent, we ought to sort values of the mappings, which is tricky for a Map can only sort by keys.\nThus, we need to utilize additional data structures.\nIn the code below, we establish a TreeMap, which map the corresponding value(frequency) to the keys(elements) of the map. \n**Essence**\n```\nmap <key : element, value : frequency>\ntreemap <key : frequency, value : list of elements>\nThat works as we sort values of map.\n```\n**Code**\n```\npublic List<Integer> topKFrequent(int[] nums, int k) {\n\n\tList<Integer> topK = new LinkedList<>();\n\tMap<Integer, Integer> elementToFrequency = new HashMap<>(); // key is element value, value is frequency of the element\n\tMap<Integer, List<Integer>> frequencyToElements = new TreeMap<>(Collections.reverseOrder()); // key is frequency, value is a list of elements with the same frequency\n\t\n\tfor (int num : nums) {\n\t\telementToFrequency.put(num, elementToFrequency.getOrDefault(num, 0) + 1);\n\t}\n\tfor (int num : elementToFrequency.keySet()) {\n\t\tint freq = elementToFrequency.get(num);\n\t\tfrequencyToElements.putIfAbsent(freq, new ArrayList<>());\n\t\tfrequencyToElements.get(freq).add(num);\n\t}\n\t\n\tfor (List<Integer> value : frequencyToElements.values()) {\n\t\tif (value.size() + topK.size() <= k) {\n\t\t\ttopK.addAll(value);\n\t\t}\n\t\telse {\n\t\t\tint countNeeded = k - topK.size();\n\t\t\tfor (int i = 0; i < countNeeded; i++) {\n\t\t\t\ttopK.add(value.get(i));\n\t\t\t}\n\t\t}\n\t\tif (topK.size() == k) {\n\t\t\treturn topK;\n\t\t}\n\t}\n\treturn topK;\n}\n\n```\nI appreciate your **VOTE UP** (\u02CAo\u0334\u0336\u0337\u0324\u2304o\u0334\u0336\u0337\u0324\u02CB)
11
0
[]
1
top-k-frequent-elements
C# Solution with comments - O(n)
c-solution-with-comments-on-by-geraltofs-9k8d
\t\t\tpublic int[] TopKFrequent(int[] nums, int k)\n\t\t\t{\n\t\t\t\t// Initialize an array to store the result\n\t\t\t\tint[] result = new int[k];\n\t\t\t\t//
geraltofsparta
NORMAL
2023-01-21T12:02:53.766216+00:00
2023-01-21T12:02:53.766257+00:00
2,379
false
\t\t\tpublic int[] TopKFrequent(int[] nums, int k)\n\t\t\t{\n\t\t\t\t// Initialize an array to store the result\n\t\t\t\tint[] result = new int[k];\n\t\t\t\t// Initialize a dictionary to store the frequency of each element\n\t\t\t\tDictionary<int, int> countDict = new Dictionary<int, int>();\n\n\t\t\t\t// Count the frequency of each element in the input array\n\t\t\t\tfor (int i = 0; i < nums.Length; i++)\n\t\t\t\t{\n\t\t\t\t\tif (countDict.ContainsKey(nums[i]))\n\t\t\t\t\t{\n\t\t\t\t\t\tcountDict[nums[i]]++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcountDict.Add(nums[i], 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Initialize an array of lists to group elements by their frequency\n\t\t\t\tList<int>[] freq = new List<int>[nums.Length + 1];\n\n\t\t\t\t// Initialize the lists in the array\n\t\t\t\tfor (int i = 0; i < freq.Length; i++)\n\t\t\t\t{\n\t\t\t\t\tfreq[i] = new List<int>();\n\t\t\t\t}\n\n\t\t\t\t// Add elements to the appropriate list based on their frequency\n\t\t\t\tforeach (var keyval in countDict)\n\t\t\t\t{\n\t\t\t\t\tfreq[keyval.Value].Add(keyval.Key);\n\t\t\t\t}\n\n\t\t\t\t// Initialize a variable to keep track of the number of elements added to the result array\n\t\t\t\tint countofresultelements = 0;\n\t\t\t\t// Iterate through the array of lists in descending order of frequency\n\t\t\t\tfor (int i = freq.Length - 1; i >= 1; i--)\n\t\t\t\t{\n\t\t\t\t\t// Add elements from the list to the result array\n\t\t\t\t\tint elementsTobeAdded = freq[i].Count;\n\t\t\t\t\twhile (elementsTobeAdded > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult[countofresultelements] = freq[i][elementsTobeAdded - 1];\n\t\t\t\t\t\telementsTobeAdded--;\n\t\t\t\t\t\tcountofresultelements++;\n\t\t\t\t\t}\n\t\t\t\t\t// If k elements have been added, break out of the loop\n\t\t\t\t\tif (countofresultelements == k)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Return the result array\n\t\t\t\treturn result;\n\n\t\t\t}
10
0
['C', 'Bucket Sort', 'C#']
1
top-k-frequent-elements
Hash-Map✔ Easy to Under-Stand in Java☕ Solution
hash-map-easy-to-under-stand-in-java-sol-a17s
Do Upvote if you liked it!!\n*\n\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n int[] ans = new int[k];\n //create a map\
hirentimbadiya74
NORMAL
2022-08-31T12:11:45.722503+00:00
2022-08-31T12:11:45.722546+00:00
1,097
false
**Do Upvote if you liked it!!**\n****\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n int[] ans = new int[k];\n //create a map\n HashMap<Integer, Integer> map = new HashMap<>();\n // put every element with its frequency \n for (int i = 0; i < nums.length; i++) {\n map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);\n }\n int i = 0;\n // take the maximum frequent element and store it in array\n while (i < k) {\n // find the max key\n int max = findMax(map);\n ans[i] = max;\n //now remove the max key from map\n map.remove(max);\n i++;\n }\n return ans;\n }\n static int findMax(HashMap<Integer, Integer> map) {\n int val = -1;\n int max = 0;\n // iterate over the hashmap \n for (Map.Entry<Integer, Integer> key : map.entrySet()) {\n if (max < key.getValue()) {\n val = key.getKey();\n max = key.getValue();\n }\n }\n return val;\n }\n}\n```\n****\n# JAVA
10
0
['Java']
0
top-k-frequent-elements
C++| Priority Queue
c-priority-queue-by-bharath_2098-sqcu
\n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n vector<int>res;\n map<int,int>m;\n priority_queue
bharath_2098
NORMAL
2020-07-17T08:23:46.086107+00:00
2020-07-17T08:23:46.086160+00:00
598
false
```\n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n vector<int>res;\n map<int,int>m;\n priority_queue<pair<int,int>>j;\n \n \n for(int i=0;i<nums.size();i++)\n m[nums[i]]++;\n \n for(auto i:m)\n j.push({i.second,i.first});\n \n for(int i=1;i<=k;i++)\n {res.push_back(j.top().second);\n j.pop();\n }\n\n \n return res;\n \n }\n};\n/*\nPriority queue stores the greatest element at the top\nexample;[1,1,1,2,2,3]\npriority queue: [{3,1},{2,2},{1,3}]\n*/\n```
10
4
[]
2
top-k-frequent-elements
[Python] Simple Solution using heap
python-simple-solution-using-heap-by-101-y4ud
\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n ## RC ##\n ## APPROACH : HEAP ##\n # logic : #\n
101leetcode
NORMAL
2020-06-21T22:11:04.474626+00:00
2020-06-21T22:11:04.474660+00:00
2,482
false
```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n ## RC ##\n ## APPROACH : HEAP ##\n # logic : #\n # 1. we store value = (frequency, key) pair in heap\n # 2. by default heapq in python is min heap. It is sorted based on value[0].\n # 3. so we multiply -1 with frequency, so as to get maximum frequent element from value[1] (as heap return minimum and we stored with negative sign)\n \n\t\t## TIME COMPLEXITY : O(NxK) ##\n\t\t## SPACE COMPLEXITY : O(N) ##\n \n import heapq\n heap = []\n count = collections.Counter(nums)\n ans = []\n for i in set(nums):\n heapq.heappush(heap,(-1 * count[i], i))\n return [ heapq.heappop(heap)[1] for _ in range(k) ]\n \n```
10
1
['Python', 'Python3']
3
top-k-frequent-elements
Python 44ms beat 100%
python-44ms-beat-100-by-joonyi-eu76
\nclass Solution(object):\n def topKFrequent(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n
joonyi
NORMAL
2018-07-06T04:59:14.352557+00:00
2018-08-25T20:42:53.155051+00:00
1,904
false
```\nclass Solution(object):\n def topKFrequent(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n """\n dict = {}\n for num in nums:\n if num in dict:\n dict[num] += 1\n else:\n dict[num] = 1\n\n bucket = [[] for _ in range(len(nums)+1)]\n for key, val in dict.items():\n bucket[val].append(key)\n\n ret = []\n for row in reversed(bucket):\n if not row:\n continue\n else:\n for i in range(len(row)):\n ret.append(row[i])\n if len(ret) == k:\n return ret\n```\nUse dict to count the frequency of the numbers, then put them into a bucket where index represents frequency. The higher the index, the higher the frequency, so loop from the end of the bucket to build the return list. Scan through the list three times, so O(3n)
10
0
[]
4
top-k-frequent-elements
6 Lines concise C++ (STL functional programming style)
6-lines-concise-c-stl-functional-program-ocoq
I personally like to heavily use STL and C++ functional programming. Not saying this is the coding style good for all people, just want to show another C++ prog
fentoyal
NORMAL
2016-05-12T04:52:02+00:00
2018-10-13T03:45:13.700021+00:00
1,399
false
I personally like to heavily use STL and C++ functional programming. Not saying this is the coding style good for all people, just want to show another C++ programming style. It's easy to write concise code with this style, but sometimes it may look awkward to people unfamiliar with it.\n \n class Solution {\n public:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n unordered_map<int, int> my_map;\n for_each (begin(nums), end(nums), [&my_map](int i){ my_map[i]++;});\n vector<pair<int, int>> pv(begin(my_map), end(my_map));\n nth_element(begin(pv), begin(pv)+k, end(pv), [](pair<int, int> a, pair<int, int> b){return a.second > b.second;});\n vector<int> result;\n transform(begin(pv), begin(pv)+k, back_inserter(result), [](pair<int, int> a){return a.first;});\n return result;\n }\n };
10
0
[]
1
top-k-frequent-elements
Java8 functional solution
java8-functional-solution-by-decaywood-x4qz
public static List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> counter = new HashMap<>();\n for (int num : nums) {\n
decaywood
NORMAL
2016-05-14T01:18:58+00:00
2016-05-14T01:18:58+00:00
2,585
false
public static List<Integer> topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> counter = new HashMap<>();\n for (int num : nums) {\n counter.putIfAbsent(num, 0);\n counter.computeIfPresent(num, (key, oldVal) -> oldVal + 1);\n }\n return counter.entrySet()\n .stream()\n .sorted(Comparator.comparing(Map.Entry<Integer, Integer>::getValue).reversed())\n .limit(k)\n .map(Map.Entry::getKey)\n .collect(Collectors.toList());\n }
10
0
[]
4
top-k-frequent-elements
Java Solution. Use HashMap and PriorityQueue
java-solution-use-hashmap-and-priorityqu-ts46
public class Solution {\n // supply a new implementation for Map.Entry Comparator\n class EntryComparator<K, V extends Comparable<V>> \n im
zhexuany
NORMAL
2016-05-22T22:59:15+00:00
2018-10-03T00:52:50.994735+00:00
7,548
false
public class Solution {\n // supply a new implementation for Map.Entry Comparator\n class EntryComparator<K, V extends Comparable<V>> \n implements Comparator<Map.Entry<?, V>> {\n public int compare(Map.Entry<?, V> left, Map.Entry<?, V> right) {\n // Call compareTo() on V, which is known to be a Comparable<V>\n return right.getValue().compareTo(left.getValue());\n } \n }\n \n public List<Integer> topKFrequent(int[] nums, int k) {\n // Priority Queue's size is k, hence the run time for this case is just O(lgK).\n PriorityQueue<Map.Entry<Integer, Integer>> kFrequent = new PriorityQueue<>(k,\n // override Comprator class \n new Comparator<Map.Entry<Integer, Integer>>() {\n public int compare(Map.Entry<Integer, Integer> left, Map.Entry<Integer, Integer>right){\n return right.getValue().compareTo(left.getValue());\n }\n }\n );\n HashMap<Integer, Integer> map = new HashMap<>();\n for(int i : nums){\n map.putIfAbsent(num, 0);\n // if key is already in the map, then increase the counter\n map.computeIfPresent(num, (key, oldVal) -> oldVal + 1);\n }\n //use priority queue to find kFrequent\n for(Map.Entry<Integer, Integer> mapEntry : map.entrySet()){\n kFrequent.offer(mapEntry);\n }\n List<Integer> returnList = new ArrayList<>();\n for(int i = 0; i < k; i++){\n // in practice, we need check operation is null or not\n //System.out.println(kFrequent.poll());\n returnList.add(kFrequent.poll().getKey());\n }\n return returnList;\n }\n }
10
2
['Java']
3