Recency-Evicting Store Simulation Plus Graph Group Tally
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a fixed-size recency-evicting key-value store from a command log, and separately count connected groups in an undirected graph, returning both results together.
This task combines two independent sub-problems. Your function must solve both and return the results together.
Part A: Recency-evicting store
A store holds integer keys mapped to integer values and has a fixed capacity. It is driven by a log of commands, given as two parallel lists: operations (command names) and arguments (the argument list for each command). The i-th command is operations[i] with arguments arguments[i].
The supported commands are:
"LRUCache"with arguments[capacity]: create an empty store with the given positive capacity. OutputNonefor this command."put"with arguments[key, value]: storevalueunderkey.- If
keyalready exists, overwrite its value. No eviction happens. - If
keyis new and the store is already full, first remove the least recently used key, then insert the new one. - In either case,
keybecomes the most recently used key. - Output
Nonefor this command.
- If
"get"with arguments[key]: ifkeyexists, output its value and make it the most recently used key. Otherwise output-1(recency is unchanged).
Each command contributes exactly one entry to the output list, in the order the commands appear. Every get and put should run in O(1) average time.
Part B: Count connected groups
You are given an integer n and a list edges. Nodes are labeled 0 to n - 1. Each edges[i] = [a, b] is an undirected connection between nodes a and b. Count the connected components of this graph. A node with no edges is its own component. Self-loops ([a, a]) and duplicate edges may appear and must not affect correctness.
Return value
Return a dictionary with two keys:
"cache": the list of outputs from Part A, one per command."components": the integer component count from Part B.
Constraints
operationsandargumentshave the same length, up to about 10^5.- The first command is
"LRUCache", and capacity is at least 1. - Keys and values are integers.
1 <= n <= 10^5, with about up to 10^5 edges.- For every edge,
0 <= a, b < n. - Both parts are independent: the graph does not depend on the store, and vice versa.
Examples
Example 1
Input: simulate_store_and_count_groups(['LRUCache', 'put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'], [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]], 5, [[0, 1], [1, 2], [3, 4]])
Output: {'cache': [None, None, None, 1, None, -1, None, -1, 3, 4], 'components': 2}
Example 2
Input: simulate_store_and_count_groups(['LRUCache', 'put', 'put', 'put', 'get', 'get'], [[2], [1, 10], [2, 20], [1, 11], [2], [1]], 4, [[0, 1]])
Output: {'cache': [None, None, None, None, 20, 11], 'components': 3}
Hints
Hint 1
For the store, you need constant-time lookup by key and constant-time reordering by recency. An ordered hash map, or a hash map plus a doubly linked list, does both.
Hint 2
Be careful with `put` on an existing key: it should refresh recency and overwrite the value, but never trigger eviction. Evict only when a genuinely new key pushes the size beyond capacity.
Hint 3
For the graph, start with `n` components and merge with Union-Find (or run a BFS/DFS from each unvisited node). Self-loops and duplicate edges naturally cause no extra merges, and isolated nodes are already counted.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part A (recency-evicting store). Keep the entries in an ordered hash map where the order of entries reflects recency: the front is the least recently used and the back is the most recently used.
get: if the key is missing, output-1. Otherwise move it to the back and output its value.puton an existing key: overwrite the value and move it to the back. The size does not change, so there is no eviction.puton a new key: insert it at the back. If the size now exceeds the capacity, remove the entry at the front.LRUCache: reset the store and record the capacity.
Each command appends exactly one output (None for LRUCache and put, the value or -1 for get).
Part B (components). Use Union-Find with path compression (path halving) and union by size. Start with n components. For each edge, find the roots of both endpoints. If they differ, merge them and decrement the component count. Self-loops and duplicate edges find equal roots and change nothing. Isolated nodes are never merged, so they remain counted as separate components.
Why it is correct
The ordered map always keeps keys sorted by last use, since every successful access or write moves the key to the back. Eviction removes the front, which is by definition the least recently used key, and only happens when a new key causes an overflow. For the graph, each successful union joins two distinct components, reducing the count by exactly one, and the final count equals the number of distinct roots.
Complexity
- Part A: O(1) average per command, O(capacity) space.
- Part B: O((n + m) · α(n)) time, which is effectively linear, and O(n) space.
- Overall: O(q + (n + m) · α(n)) time for
qcommands andmedges.
Reference solution
from collections import OrderedDict
from typing import Dict, List
def simulate_store_and_count_groups(operations: List[str], arguments: List[List[int]], n: int, edges: List[List[int]]) -> Dict[str, object]:
store = OrderedDict()
capacity = 0
outputs = []
for op, args in zip(operations, arguments):
if op == "LRUCache":
capacity = args[0]
store = OrderedDict()
outputs.append(None)
elif op == "get":
key = args[0]
if key not in store:
outputs.append(-1)
else:
store.move_to_end(key)
outputs.append(store[key])
elif op == "put":
key, value = args
if key in store:
store[key] = value
store.move_to_end(key)
else:
store[key] = value
if len(store) > capacity:
store.popitem(last=False)
outputs.append(None)
parent = list(range(n))
size = [1] * n
components = n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in edges:
ra = find(a)
rb = find(b)
if ra != rb:
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
components -= 1
return {"cache": outputs, "components": components}