Feature #6: Fetch Most Frequently Watched Titles
Explore how to build a data structure that fetches the most frequently watched titles in Elixir. Learn to maintain frequency counts using hash maps and doubly linked lists, handle evictions when capacity is reached, and optimize for constant time operations. This lesson guides you through implementing and understanding the logic behind managing access frequencies and recency in streaming applications.
We'll cover the following...
Description
This feature and the one we discussed before are almost similar, but now the titles are maintained in order of viewing/access frequency. When the data structure is at capacity, a newly inserted item will replace the least frequently accessed item. In the case of a tie, the least recently accessed item should be replaced.
Let’s say that a user has gone through the following titles:
We need to design a structure that takes the ID of the movies and adds them to our structure. It also needs to fetch a movie title when accessed through its ID. We also have to consider the size of the data structure and maintain the least frequently watched property. This means that when our structure is at its capacity then a newly inserted item will replace the item whose frequency count is the lowest.
Here is an illustration of this process. When we insert the value 5, then the element with the least frequency is 1. Hence, it gets replaced by 5.
Solution
In non-functional languages, like C#/Java, one would solve this problem with the help of hashtable and doubly-linked lists. However, in Elixir, there is no straightforward way to create such cyclic data structures.
We’ll build this structure on top of the one from the previous lesson. We will also use a Hash Map and a doubly linked list. In this case, we’ll also store data on how frequently titles are accessed along with their respective keys and values. We’ll append each new entry at the tail of the doubly linked list. A Hash Map will be used to keep track of the keys and their values in the linked list.
You could create a Hash Map ...