-
Notifications
You must be signed in to change notification settings - Fork 375
Closed
Labels
Description
LeetCode Username
KitchenStuff12fkngael
Problem Number, Title, and Link
- Top K Frequent Elements(https://leetcode.com/problems/top-k-frequent-elements/description/)
Bug Category
Editorial
Bug Description
The code is correctly written and the Test Cases run. But when I submit, it fails and say Wrong Answer on the second Test Case that actually ran during the Compile and Run.
I am a Premium User so I also tried running the solution given in the editorial and tried Submitting the response, and still it says Wrong Answer.
Attaching screenshots.


Language Used for Code
Java
Code used for Submit/Run operation
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// O(1) time
if (k == nums.length) {
return nums;
}
// 1. Build hash map: character and how often it appears
// O(N) time
Map<Integer, Integer> count = new HashMap();
for (int n: nums) {
count.put(n, count.getOrDefault(n, 0) + 1);
}
// init heap 'the less frequent element first'
Queue<Integer> heap = new PriorityQueue<>(
(n1, n2) -> count.get(n1) - count.get(n2));
// 2. Keep k top frequent elements in the heap
// O(N log k) < O(N log N) time
for (int n: count.keySet()) {
heap.add(n);
if (heap.size() > k) heap.poll();
}
// 3. Build an output array
// O(k log k) time
int[] top = new int[k];
for(int i = k - 1; i >= 0; --i) {
top[i] = heap.poll();
}
return top;
}
}
and
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// nums is given, have to return the K most frequent elements
// require a minheap to store the most frequent element count and the element itself.
// minheap <Integer, Integer>, iterate through nums, if a num is found in minheap, add 1 to the key and store in minheap.
// at the end, pop the elments out of minHeap if the size is greater than k.
// return the array of elements remaining in minHeap.getValue() for answer.
// time complexity: O(nlogk) and space complexity: O(k)
// creating a hashmap to store the frequency of each number
Map<Integer, Integer> frequencyOfNums = new HashMap<>();
for (int num: nums) {
if(frequencyOfNums.containsKey(num)) {
frequencyOfNums.put(num, frequencyOfNums.get(num)+1);
} else {
frequencyOfNums.put(num, 1);
}
}
// Create a MinHeap to store the elements in hashmap in heap with pair and compare
PriorityQueue<Pair<Integer, Integer>> minHeap = new PriorityQueue<>(
(a,b) -> Integer.compare(a.getKey(), b.getKey()));
for (Map.Entry<Integer,Integer> entry: frequencyOfNums.entrySet()) {
minHeap.add(new Pair<>(entry.getValue(), entry.getKey()));
}
while (minHeap.size() > k) {
minHeap.poll();
}
// create resultant array to return ans.
int[] result = new int[k];
for (int i = 0; i < k; i++) {
Integer frequentNumber = minHeap.poll().getValue();
result[i] = frequentNumber;
}
return result;
}
}
Expected behavior
It should be Accepted and Submitted instead of saying Wrong Answer.
Screenshots


Additional context
No response