Skip to main content

LeetCode 347. Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

Option 1 - Map to count + Sort to get top k - O(nlgn)

  1. We need to count what is the freq or how many times an item appeared.
  2. The obvious thing is for each item put it in a hashmap where
    1. Key is the item
    2. Value is the number of times it appeared
  3. Now the only thing that is left is to sort this hashtable.
  4. sorting is O(nlgn), placing everyting and counting is O(n) so this makes it overall O(nlgn)

Option 2 - Improvement over option 1 - Instead of sorting use a Heap

  1. This is a common thing when you need to sort but the core of the problem is not sorting but as in this example only get top k then we could utilize a heap.
    1. We still build a map as in option 1 which takes O(n) this is the counting map.
    2. Building a heap heapify takes O(n)
    3. Remove each item from the heap is O(lg(n)) until we removed k items - as each pop from a heap is lg(n)
    4. Overall this makes it klg(n) + n which can be better than nlgn if k < n

Option 3 - O(n) - Use buckets for finding the top k

  1. Start as usual build a hashtable for counting how many times each item appears this would be O(n)
  2. Now create an array [] of size of number of items we have here index i would be a list of the number occuring i times
    1. [].get[7] --> [the items that appeared 7 times]
  3. And as you see to get the top k we just need to traverse the top k elements of this list
  4. Overall this means O(n) for creating the hashtable and O(n) for traversing this buckets list.

Here is the actual implementation of the buckets solution:

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        # step 1 - put it in the map 
        #         [1,1,3,4] --> {
        #                             {1 --> 2}
        #                           , {3 --> 4}
        #                           , {4 --> 1}
        #                        }
        # 
        # step 2 prepare buckets [0, ... nums.length ] -> a number can appear at most nums.
        #        Bonus - buckets already sorted by index last bucket is one with highest number if count.
        # 
        # Step 3 Read buckets in reverse order.
        
        appearances = {} # map {number -> # times appears }
        for x in nums:
            appearances[x] = 1 + appearances.get(x, 0)
        
        buckets = [[] for i in range(len(nums) + 1)] # [] - An array of arrays, we are going to keep all the x that are in each bucket appeared number of times as index of bucket.
        for (x, num_appearances) in appearances.items():
            buckets[num_appearances].append(x)
            
        res = []    
        for i in range(len(buckets) - 1, 0, -1):
            for x in buckets[i]:
                res.append(x)
                if (len(res) == k):
                    return res;


Comments

Popular posts from this blog

Functional Programming in Scala for Working Class OOP Java Programmers - Part 1

Introduction Have you ever been to a scala conf and told yourself "I have no idea what this guy talks about?" did you look nervously around and see all people smiling saying "yeah that's obvious " only to get you even more nervous? . If so this post is for you, otherwise just skip it, you already know fp in scala ;) This post is optimistic, although I'm going to say functional programming in scala is not easy, our target is to understand it, so bare with me. Let's face the truth functional programmin in scala is difficult if is difficult if you are just another working class programmer coming mainly from java background. If you came from haskell background then hell it's easy. If you come from heavy math background then hell yes it's easy. But if you are a standard working class java backend engineer with previous OOP design background then hell yeah it's difficult. Scala and Design Patterns An interesting point of view on scala, is

Alternatives to Using UUIDs

  Alternatives to Using UUIDs UUIDs are valuable for several reasons: Global Uniqueness : UUIDs are designed to be globally unique across systems, ensuring that no two identifiers collide unintentionally. This property is crucial for distributed systems, databases, and scenarios where data needs to be uniquely identified regardless of location or time. Standardization : UUIDs adhere to well-defined formats (such as UUIDv4) and are widely supported by various programming languages and platforms. This consistency simplifies interoperability and data exchange. High Collision Resistance : The probability of generating duplicate UUIDs is extremely low due to the combination of timestamp, random bits, and other factors. This collision resistance is essential for avoiding data corruption. However, there are situations where UUIDs may not be the optimal choice: Length and Readability : UUIDs are lengthy (typically 36 characters in their canonical form) and may not be human-readable. In URLs,

Bellman Ford Graph Algorithm

The Shortest path algorithms so you go to google maps and you want to find the shortest path from one city to another.  Two algorithms can help you, they both calculate the shortest distance from a source node into all other nodes, one node can handle negative weights with cycles and another cannot, Dijkstra cannot and bellman ford can. One is Dijkstra if you run the Dijkstra algorithm on this map its input would be a single source node and its output would be the path to all other vertices.  However, there is a caveat if Elon mask comes and with some magic creates a black hole loop which makes one of the edges negative weight then the Dijkstra algorithm would fail to give you the answer. This is where bellman Ford algorithm comes into place, it's like the Dijkstra algorithm only it knows to handle well negative weight in edges. Dijkstra has an issue handling negative weights and cycles Bellman's ford algorithm target is to find the shortest path from a single node in a graph t