KatInterview

Simulate Key-Value Operations

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingarraysstringshash-table

Last updated

Process a series of insertion, update, and deletion instructions on a key-value store and return the final contents ordered by key.

You are tasked with maintaining a simple key-value store that supports three types of sequential modifications:

  1. ["INSERT", key, value]: Adds key with its corresponding value to the store. If key is already present in the store, this command is skipped.
  2. ["UPDATE", key, value]: Modifies the value of an existing key to value. If key is not currently in the store, this command is skipped.
  3. ["REMOVE", key]: Deletes key and its value from the store. If key does not exist in the store, this command is skipped.

Beginning with an empty key-value store, execute all instructions in the given order. Return the resulting state of the store as a list of [key, value] pairs, sorted lexicographically by key.

Constraints

  • 1 <= len(operations) <= 10^5
  • 1 <= len(key), len(value) <= 50
  • key and value consist only of alphanumeric characters ([a-zA-Z0-9]).
  • Each command is validly formatted as one of ["INSERT", key, value], ["UPDATE", key, value], or ["REMOVE", key].

Examples

Example 1

Input: process_store_operations([['INSERT', 'apple', '10'], ['INSERT', 'banana', '20'], ['UPDATE', 'apple', '15'], ['INSERT', 'apple', '30'], ['REMOVE', 'banana'], ['UPDATE', 'orange', '5'], ['INSERT', 'cherry', '25']])

Output: [['apple', '15'], ['cherry', '25']]

Example 2

Input: process_store_operations([['REMOVE', 'missing_key'], ['INSERT', 'k1', 'v1'], ['REMOVE', 'k1'], ['UPDATE', 'k1', 'v2']])

Output: []

Hints

Hint 1

Use a hash table (dictionary) to track the current state of each key with O(1) lookup and modification times.

Hint 2

Pay close attention to the conditions: INSERT does nothing if the key already exists, while UPDATE does nothing if the key is missing.

Hint 3

Instead of maintaining order after every command, sort the keys once after processing all instructions.