← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
Given a non-empty array of integers, return the k most frequent elements.
Example 1: ` Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Explanation:
Example 2: ` Input: nums = [1], k = 1 Output: [1] Explanation:
Note:
Here's a Python solution using a hash table and a max heap:
`python import heapq
class Solution: def topKFrequent(self, nums, k): count = {} for num in nums: count[num] = count.get(num, 0) + 1
# Create a max heap
max_heap = [(-freq, num) for num, freq in count.items()]
heapq.heapify(max_heap)
result = []
for _ in range(k):
result.append(heapq.heappop(max_heap)[1])
return result
`
This solution has a time complexity of O(n log k), where n is the length of the input array. The space complexity is O(n), as we need to store the count of each element in a hash table.