KatInterview

Running Tally per Label from a Replayed Call Log

Data Structure DesignAuto-graded · 18 test cases
EasyAuto-gradedData Structure Designhash-mapsimulationdesign

Last updated

Replay a log of increment calls and report, for each call, how many times its key has appeared so far, testing hash map counting and a simple operation-dispatch design.

You are given a recorded log of calls made to a small counting component. The component keeps a tally for each string key. Every call to it bumps the tally of one key by one and reports the updated tally.

The log is split into two parallel lists of equal length:

  • operations[i] is the name of the i-th call.
  • arguments[i] is the list of arguments passed to that call.

The only call name that appears is "incrementAndGet". Its argument list holds exactly one string, the key. When this call is made, the tally for that key goes up by one (a key never seen before starts at 0, so its first call yields 1), and the call's result is the key's tally immediately after the increase. That is, the result equals the number of calls so far, including this one, that used that key.

Replay the log from the first call to the last, in order, and return a list with the result of each call, in the same order as the log.

Calls are applied strictly one after another, and different keys never affect each other. Tallies start empty. If a call name other than "incrementAndGet" is ever encountered, raise a ValueError.

Constraints

  • operations and arguments have the same length.
  • Each element of arguments is a list whose first element is the key; keys are strings and are compared exactly (case-sensitive).
  • The number of distinct keys is not known in advance and may be large.
  • Every tally fits in a 64-bit signed integer.
  • The returned list has one integer per call, in log order.

Examples

Example 1

Input: replay_key_tallies(['incrementAndGet', 'incrementAndGet', 'incrementAndGet'], [['a'], ['b'], ['a']])

Output: [1, 1, 2]

Example 2

Input: replay_key_tallies(['incrementAndGet', 'incrementAndGet', 'incrementAndGet', 'incrementAndGet'], [['x'], ['x'], ['x'], ['x']])

Output: [1, 2, 3, 4]

Example 3

Input: replay_key_tallies(['incrementAndGet', 'incrementAndGet', 'incrementAndGet', 'incrementAndGet', 'incrementAndGet'], [['cat'], ['dog'], ['cat'], ['cat'], ['dog']])

Output: [1, 1, 2, 3, 2]

Hints

Hint 1

Keep a dictionary that maps each key to how many times you have seen it so far.

Hint 2

For an unseen key, treat its current tally as 0, add one, store it, and append the stored value to the output.

Hint 3

One pass over the log is enough; each lookup and update is expected constant time, so overall work is linear in the number of calls.