KatInterview

Rolling Up Page Views Through Hostname Suffixes

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringshash-mapstringsparsing

Last updated

Aggregate per-host view counts so every host and each of its parent suffixes gets the total of itself and all hosts beneath it, using suffix enumeration and a hash map.

Rolling Up Page Views Through Hostname Suffixes

A web analytics service records traffic as lines of text. Each line has the form "<views> <hostname>", for example "900 google.com". A hostname is a sequence of labels separated by dots. Each hostname sits beneath every suffix made of its trailing labels: mail.google.com is beneath google.com, which is beneath com.

Write a function that computes, for every hostname that appears in the hierarchy, the total number of views for that hostname plus all hostnames beneath it.

Task

Given a list of record strings, return a dictionary that maps each hostname to its rolled-up view total.

  • The result must contain every hostname that appears in an input record, and also every dot-separated suffix of each such hostname (made of whole trailing labels).
  • The total for a key is the sum of the view counts of all input records whose hostname is equal to that key or ends with . followed by that key.
  • If the same hostname appears in several records, their counts are added together.
  • Suffixes are formed on label boundaries only. For instance, oogle.com is not a suffix of google.com.
  • A hostname with a single label (such as com) has only itself as a suffix.
  • The order of keys in the returned dictionary does not matter.

Input

  • records: a list of strings, each in the format "<views> <hostname>", with the count and hostname separated by whitespace.

Output

  • A dictionary mapping each hostname (string) to its total view count (integer).

Constraints

  • 1 <= number of records <= 10,000
  • Each hostname has length between 1 and 100 characters
  • 1 <= views per record <= 1,000,000
  • Hostnames may repeat across records, and different hostnames may share suffixes

Examples

Example 1

Input: roll_up_views(['900 google.com', '50 mail.google.com'])

Output: {'google.com': 950, 'com': 950, 'mail.google.com': 50}

Example 2

Input: roll_up_views(['10 apple.com', '20 banana.com'])

Output: {'apple.com': 10, 'com': 30, 'banana.com': 20}

Hints

Hint 1

You do not need to build an explicit tree. Think about which keys a single record contributes to.

Hint 2

A record for a.b.c contributes its count to a.b.c, b.c and c. Split the hostname on dots and generate each trailing slice of the label list.

Hint 3

Use a dictionary and add to the existing value (rather than overwriting) so repeated hostnames and shared suffixes accumulate correctly.