← 返回 google 的题目列表Count Nested Key Pairs and Return Most Frequent Inner Key
类型:online_judge
Problem: Count Nested Key Pairs and Return the Most Frequent Inner Key
You are given a list of records records, where each record is a two-element list/tuple [outer, inner].
Implement the following features:
Count the number of occurrences of every (outer, inner) pair and return a nested dictionary:
{
outer1: {inner1: count, inner2: count, ...},
outer2: {inner3: count, ...},
...
}
Follow-up 1: Based on the nested dictionary, return the most frequent inner for every outer:
{
outer1: most_frequent_inner,
outer2: most_frequent_inner,
...
}
If multiple inner keys have the same maximum count, return the lexicographically smallest one for deterministic output.
Follow-up 2: Analyze the time and space complexity.
Follow-up 3: Given another batch of records new_records, update the existing nested dictionary incrementally, then return the updated counts and the updated most frequent inner for each outer.
Input Format
For runnable testing, use the following input format:
n
outer_1 inner_1
outer_2 inner_2
...
outer_n inner_n
m
new_outer_1 new_inner_1
new_outer_2 new_inner_2
...
new_outer_m new_inner_m
n is the number of initial records.
The next n lines each contain two strings: outer inner.
m is the number of new records.
The next m lines each contain two strings: outer inner.
Output Format
Print 4 lines of JSON:
The nested count dictionary for the initial records.
The most frequent inner for each outer before updates.
The nested count dictionary after applying updates.
The most frequent inner for each outer after updates.
For easier judging, all dictionary keys should be sorted lexicographically in the output.
Constraints
0 <= n, m <= 100000
outer and inner are non-empty strings containing only letters, digits, and underscores.
Each string has length at most 50.
The total number of records is at most 200000.
Example
Input:
5
a b
a b
a c
f g
f p
3
f g
f g
a c
Output:
{"a":{"b":2,"c":1},"f":{"g":1,"p":1}}
{"a":"b","f":"g"}
{"a":{"b":2,"c":2},"f":{"g":3,"p":1}}
{"a":"b","f":"g"}
Example
Input
5
a b
a b
a c
f g
f p
3
f g
f g
a c
Output
{"a":{"b":2,"c":1},"f":{"g":1,"p":1}}
{"a":"b","f":"g"}
{"a":{"b":2,"c":2},"f":{"g":3,"p":1}}
{"a":"b","f":"g"}