Most Popular Video Creator - Hashmap [JS]

Description 

Solution: Hashmap

In a hashmap, store the following for each person:

  1. The sum of views
  2. The id of the video with maximum views
  3. The maximum number of views

Then, go through each person and record the highest number of views and the people with the maximum views.

Time Complexity: O(n) 725ms
Space Complexity: O(n) 144.6MB

var mostPopularCreator = function(creators, ids, views) {
  let n = creators.length, map = {}; // { creator: [sum of views, maxId, maxViews] }
  for (let i = 0; i < n; i++) {
    let creator = creators[i];
    if (!map[creator]) map[creator] = [views[i], ids[i], views[i]];
    else {
      map[creator][0] += views[i];
      let [_, maxId, maxViews] = map[creator];
      if (views[i] > maxViews) {
        map[creator][2] = views[i];
        map[creator][1] = ids[i];
      } else if (views[i] === maxViews) {
        map[creator][1] = ids[i] < maxId ? ids[i] : maxId;
      }
    }
  }  
  let bestCreators = [], maxViews = 0;
  for (let creator in map) {
    let totalViews = map[creator][0];
    if (totalViews > maxViews) {
      maxViews = totalViews;
      bestCreators = [[creator, map[creator][1]]];
    } else if (totalViews === maxViews) {
      bestCreators.push([creator, map[creator][1]]);
    }
  }
  return bestCreators;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]