Given a bunch of key-value pairs, for each unique key find 1) the number of values and 2) the lexicographically greatest value.
Input is an array of strings, each with a key and a value separated by a space:
Output is an array of strings with unique keys followed by a colon, the total number of values, a comma, and the lexicographically greatest of the values associated with that key in the input:
The order or strings in the output is insignificant; these same strings in a different order are also a correct output.
Order of strings in the output does not matter.
● Keys and values consist of lowercase letters and digits.
● Keys can repeat.
● Values can repeat.
We provided one solution. It uses a hashmap to store the current number of values and the lexicographically greatest value for each key found so far as we iterate over the input. To process another string from the input we identify the key and value and then look for a value already present in the hashmap for this key. If one is found, we increment the number of values for this key and make sure the hashmap has the lexicographically greater value of the one it already has and one from the current input string. If no value for the current key is found in the hashmap, we simply put the current one there.
After processing all the input strings in this way, we just need to convert the hashmap data to the output format.
O(n*(longest key + longest value)) because comparing two strings of length k takes O(k) time.
Auxiliary Space Used:
O(n*(longest key + longest value)) because of the hashmap.
O(n*(longest key + longest value)).