Top K Frequent Elements

Advanced

Top K Frequent Elements

Hey there, little coder! Let's play a fun game with numbers. Imagine you have a collection of numbers, and you want to find out which numbers appear the most frequently in your collection. Isn't that cool? We'll make a magical Python function to solve this puzzle!

What should the function do?

You need to write a function called top_k_frequent() that accepts two arguments:

  1. A list of numbers called nums.
  2. An integer k, which tells you how many top frequent numbers you need to find.

The function will return a list of k numbers that are the most frequent in the nums list.

Let's See Some Examples!

# Example 1 nums = [1, 1, 1, 2, 2, 3] k = 2 # The numbers 1 and 2 are the most frequent. # So, the function should return: [1, 2] # Example 2 nums = [4, 4, 4, 1, 1, 2, 2, 3] k = 3 # The numbers 4, 1, and 2 are the most frequent. # So, the function should return: [4, 1, 2] # Example 3 nums = [5, 5, 5, 6, 6, 6, 7] k = 1 # The numbers 5 and 6 have the same frequency # but we return the first one found - 5. # [5] or [6] is fine, we will take the first.

Ready, Set, Code!

Use any magical way you think will work! Use loops, lists, dictionaries to keep count, and lists to store the most frequent numbers! Let your imagination fly!

Happy coding!

Geek
Inputs

Arg 1:

[1,1,1,2,2,3]

Arg 2:

2
Expected Output
[1, 2]
Actual Output