Problem 405532 · medium · Level 04 Non-Linear Data Structures

A Bucket With a List Hanging Off It

hashing · separate chaining · simulation

A hash table with m buckets resolves collisions by separate chaining: bucket key % m holds a list of the keys that landed there, in the order they arrived.

Write chain_table(ops, m). Each operation is a pair:

  • ("add", key) — append key to the end of its bucket, unless that bucket already holds it;
  • ("del", key) — remove key from its bucket if it is there, otherwise do nothing.

Return the list of m buckets after all the operations.

Examples

Input:  ops = [("add", 1), ("add", 4), ("add", 2), ("del", 1)], m = 3
Output: [[], [4], [2]]
Explanation: 1 and 4 share bucket 1 until 1 is removed; 2 sits alone in bucket 2.

Input:  ops = [("add", 5), ("add", 5), ("del", 9)], m = 2
Output: [[], [5]]
Explanation: the second add finds 5 already in the chain, and deleting a key that is absent changes nothing.

Constraints

  • 1 <= m <= 10**4, 0 <= len(ops) <= 10**5
  • 0 <= key <= 10**9

Goals

  • Resolve collisions by keeping a list per bucket
  • Keep insertions idempotent by searching the chain first
  • Delete from the middle of a chain without disturbing the rest
Starting Python…