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
`... | 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;
... | 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, ... | 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, ... | 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. --... | 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 usefu... | 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
`... | 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 (si... | 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 co... | 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
`... | 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.p... | 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... | 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,68... | 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, s... | 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. ... | 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 ... | 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 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... | 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 bu... | 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 time... | 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... | 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\... | 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) t... | 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 [... | 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 Wh... | 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 ... | 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 ... | 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... | 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 2... | 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 ... | 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 ele... | 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){... | 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 bu... | 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 p... | 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<Intege... | 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... | 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 approa... | 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));\... | 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... | 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... | 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 ... | 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\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 usin... | 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... | 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));\... | 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... | 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)... | 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... | 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 ,... | 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 ... | 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 ... | 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[] topK... | 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[](https://leetcode.com/problems/top-k-frequent-elements/submissions/1210933053?envType=study-plan-v2&env... | 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```\ncla... | 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 /... | 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(num... | 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 elem... | 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\' e... | 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 ... | 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<Ma... | 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. **Collec... | 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() -... | 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(heapma... | 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... | 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... | 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] con... | 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 e... | 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 els... | 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. $... | 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 ... | 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 PriorityQ... | 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 ... | 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 {\... | 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 ... | 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, num... | 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 ... | 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 v... | 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 =... | 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, d... | 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... | 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. ... | 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)$$ --... | 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;\... | 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.ge... | 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++) {... | 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 ... | 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 Int... | 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... | 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, whic... | 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 fre... | 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; ... | 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... | 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 # ... | 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[... | 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 ... | 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 ... | 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... | 10 | 2 | ['Java'] | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.