Search code examples
pythonhashmap

Leetcode To K frequent elements


I am trying to solve the problem (Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.) by creating a hashmap where the key is the item in the list nums and the pair for that value is the amount of time that item appears on the list. I loop through the list then there is an if statement that checks if that item is already a key in the dictionary, if so it will add 1 to its value, and if not, it will add it as a key and give it a value of 1. When I run the code for the list nums = [1, 1, 1, 2, 2, 3], the output is completely wrong. This is the expected output {1: 3, 2: 2, 3: 1} instead I receive {1: 5, 2: 1}.

Here is my code:

nums = [1,1,1,2,2,3]
iterations = {}

for x in nums:
    if nums[x] in iterations:
        iterations[nums[x]] += 1
    else:
        iterations[nums[x]] = 1

print(iterations)

Solution

  • The corrected version of your code

     nums = [1, 1, 1, 2, 2, 3]
     iterations = {}
      
     for x in nums:
         if x in iterations:
             iterations[x] += 1
         else:
             iterations[x] = 1
    
     print(iterations)