LC347: Top K Frequent Elements; final result returns an extra element in list/array

17 views Asked by At

Leetcode 347 in Python, snippet of my code:

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dictionary = {}
        freq = [[] for i in range(len(nums) + 1)]

        for num in nums:
            dictionary[num] = dictionary.get(num, 0) + 1

        for k, v in dictionary.items():
            freq[v].append(k)
        
        result = []
        for i in range(len(freq)-1, 0, -1):
            for n in freq[i]:
                result.append(n)
                if len(result) == k:
                    return result

In the case of nums = [1,1,1,2,2,3], result list should return [1,2], but my result list is returning [1,2,3].

I found that in the following for loops, if I change the variable names to match each other, then the solution returns the correct answer.

By changing k to num, to match the variables of the for loops:

        for num in nums:
            dictionary[num] = dictionary.get(num, 0) + 1
        # num was originally k, as observed in the code snippet above
        for num, v in dictionary.items():
            freq[v].append(num)

Why is this so? Aren't separate for-loops independent of iterator variables?

0

There are 0 answers