Replay Keyed Updates and Report Per-Group Peak Values
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a log of keyed insert and query commands, keeping a running maximum for each key so single-key and all-key peak queries are answered without rescanning data.
Replay Keyed Updates and Report Per-Group Peak Values
You are given a recorded sequence of commands sent to an in-memory tracker. The tracker sorts numeric readings into named groups and remembers the largest reading seen so far in each group. Your job is to replay the commands in order and return what each command produces.
You receive two lists of equal length:
commands: a list of strings, the command names.payloads: a list of lists, wherepayloads[i]holds the arguments ofcommands[i].
Every group is identified by a string key. A group does not exist until its first reading arrives.
Commands
| Command | Payload | Effect | Output |
|---|---|---|---|
"add" | [key, value] | Record the numeric value in the group named key, creating the group if it is new. The group's peak becomes the larger of its old peak and value. | None |
"max" | [key] | Look up the current peak of the group named key. | The peak, or None if no reading was ever added to that key. |
"all_maxima" | [] | Report every existing group together with its current peak. | A list of [key, peak] pairs sorted in ascending order by key (standard string comparison). The list is empty if no groups exist. |
Notes
- Values can be negative, zero, or positive. A group whose only readings are negative has a negative peak.
- Repeated or equal values never change a peak in a harmful way: the peak is simply the largest value seen.
- A
"max"query for an unknown key does not create the group. - Any command name other than the three above is invalid; raise a
ValueErrorfor it.
Task
Return a list with one entry per command, in the same order as commands, holding the output of each command as described in the table.
Constraints
len(commands) == len(payloads)- Keys are strings; values are numbers (integers in the tests).
- Each
"add"and"max"command should run in expected O(1) time, and"all_maxima"in O(g log g) time wheregis the number of existing groups. - Do not rescan earlier readings to answer a query.
Examples
Example 1
Input: replay_group_peaks(['add', 'add', 'max', 'add', 'max', 'all_maxima'], [['a', 5], ['a', -2], ['a'], ['b', 7], ['b'], []])
Output: [None, None, 5, None, 7, [['a', 5], ['b', 7]]]
Example 2
Input: replay_group_peaks(['max', 'add', 'max', 'add', 'max'], [['missing'], ['x', -10], ['x'], ['x', -3], ['x']])
Output: [None, None, -10, None, -3]
Example 3
Input: replay_group_peaks(['add', 'add', 'add', 'all_maxima'], [['z', 4], ['a', 4], ['z', 4], []])
Output: [None, None, None, [['a', 4], ['z', 4]]]
Example 4
Input: replay_group_peaks(['add', 'max', 'all_maxima'], [['cluster-1', 0], ['cluster-1'], []])
Output: [None, 0, [['cluster-1', 0]]]
Hints
Hint 1
You never need to remember individual readings, only the largest one per key. What container maps a key to a single number?
Hint 2
On an add, compare the new value with the stored peak only if the key already exists; otherwise the new value becomes the peak. Be careful not to treat a peak of 0 or a negative peak as 'missing'.
Hint 3
For a max query use a lookup that returns None for missing keys without inserting anything. For all_maxima, sort the keys and build [key, peak] pairs fresh each time.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a dictionary that maps each key to the largest value seen for it. Nothing else about the readings has to be stored, because a maximum can be maintained incrementally.
Walk through the commands in order:
- add: if the key is new, store the value as its peak. Otherwise replace the stored peak only when the new value is strictly larger. The check uses key membership rather than truthiness, so peaks of
0or negative numbers are handled correctly. - max: look the key up with
dict.get, which returnsNonefor unknown keys and does not create an entry. - all_maxima: sort the keys and emit a
[key, peak]pair for each. A new list is built on every call, so later updates cannot alter results already returned. - anything else: raise
ValueError.
Why it is correct
The peak stored for a key is always the maximum of all values added to it so far. This holds after the first add, because that value is the only one. It is preserved by every later add, because the new maximum of a set plus one extra element is the larger of the old maximum and the new element. Queries only read this invariant, so each answer reflects exactly the readings that came before it in the log.
Complexity
addandmax: O(1) expected time.all_maxima: O(g log g) time forggroups, due to sorting, and O(g) output space.- Overall space: O(g) for the dictionary, plus the output.
Reference solution
from typing import List
def replay_group_peaks(commands: List[str], payloads: List[List]) -> List:
peaks = {}
outputs = []
for command, args in zip(commands, payloads):
if command == "add":
key, value = args
if key not in peaks or value > peaks[key]:
peaks[key] = value
outputs.append(None)
elif command == "max":
key = args[0]
outputs.append(peaks.get(key))
elif command == "all_maxima":
outputs.append([[key, peaks[key]] for key in sorted(peaks)])
else:
raise ValueError(f"unknown command: {command}")
return outputs