DEV Community

Cover image for Day 20 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 20 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/top-k-frequent-elements-in-array/1

Top K Frequent in Array

Difficulty: Medium Accuracy: 40.23%

Given a non-empty integer array arr[]. Your task is to find and return the top k elements which have the highest frequency in the array.
Note: If two numbers have the same frequency, the larger number should be given the higher priority.

Examples:
Input: arr[] = [3, 1, 4, 4, 5, 2, 6, 1], k = 2
Output: [4, 1]
Explanation: Frequency of 4 is 2 and frequency of 1 is 2, these two have the maximum frequency and 4 is larger than 1.
Input: arr[] = [7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9], k = 4
Output: [5, 11, 7, 10]
Explanation: Frequency of 5 is 3, frequency of 11 is 2, frequency of 7 is 2, frequency of 10 is 1.
Constraints:
1 ≀ arr.size() ≀ 105
1 ≀ arr[i] ≀ 105
1 ≀ k ≀ no. of distinct elements

Solution:
class Solution:
def topKFreq(self, arr, k):
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
sorted_items = sorted(freq.items(), key=lambda x: (-x[1], -x[0]))
return [x[0] for x in sorted_items[:k]]

Top comments (0)