Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
Use
Map<Date, List<Integer>> map = new HashMap<Date, List<Integer>>
Insert :
List<Integer> songsId = map.get(currentDate);
songsId.add(newSongId);
map.add(currentDate, songsId );
retrieve:
for(Map::EntrySet<Date, List<Integer>> entry : map){
if(DateWithinWeek( entry.getKey())){
for(Integer songsId : entry.getVal){
// output the result
}
}
}
Assumption: multiple users IDs with tracks they listened to in the last one week have been given to you.
Solution: Use a HashMap with UserId as the key and a Priority Queue (Max heap) of Songs based on the number of times that particular user has listened to. So the priority queue's top holds the song that was listened to the maximum number of times.
Alternatively, you could use a hashmap of treemaps reverse sorted based on the number of times a song has been listened to. Hope I am making sense.
Just got an idea, what if we set the expiry of the record to 7 days. That way every record that is there in cache is within the time limit. Then we simply have to return the top n records of all records for the user within that time frame. Does that make sense? Anybody who can suggest the code for this?
Can a caching policy with LRU be of any help here. You can use LinkedHashMap and implement the removeEldestEntry when size is more than capacity(i.e., n). Assuming those records are unique.
- Ahmed.Ebaid August 18, 2017For duplicate records, you can use a map with key equal to song name and an integer value representing the frequency of how many times the song was listened for. You can then output the first n songs with maximum frequency.