Five-Task Toolkit: Graphs, Swaps, Digits, Cache, Trees
Trees & GraphsAuto-graded · 15 test casesLast updated
Solve five small tasks in one call: count graph components, minimum swaps to sort, largest monotonic number, simulate an LRU cache, and compare two N-ary trees.
Five Tasks, One Function
Implement a single function that solves five independent sub-tasks and returns all five answers in one dictionary.
Inputs
vertex_count: number of vertices in an undirected graph, labelled0tovertex_count - 1.adjacency: a dictionary mapping a vertex label, written as a string (for example"2"), to the list of its neighbour labels (integers). Every edge appears in both endpoints' lists. A vertex with no entry has no neighbours.values: a list of distinct integers.limit: a non-negative integer.capacity: the capacity of an LRU cache.operations: a list of cache operations, each either["get", key]or["put", key, value].tree_a,tree_b: two N-ary trees, each eitherNone(empty) or a dictionary{"val": x, "children": [subtree, ...]}. A missing"children"entry means no children.
The five sub-tasks
- Connected components. Count the connected components of the graph. Isolated vertices, including those missing from
adjacency, each count as one component. Ifvertex_countis0, the answer is0. - Minimum swaps to sort. Find the minimum number of swaps of two elements (at any positions) needed to arrange
valuesin ascending order. An empty or already sorted list needs0. - Largest monotonic number. Find the largest integer that is less than or equal to
limitand whose decimal digits are in non-decreasing order from left to right. For example,332gives299, and10gives9. - LRU cache simulation. Start with an empty cache of the given
capacityand processoperationsin order.getreturns the stored value and marks that key as most recently used. If the key is absent, it returns-1.putstores or overwrites the value and marks the key as most recently used. If the cache then holds more thancapacitykeys, remove the least recently used key.- If
capacityis0,putstores nothing. - Record one result per operation: the returned value for
get, andNoneforput.
- Tree equality. Decide whether
tree_aandtree_bare identical. They are identical when they have the same shape and equalvalat every corresponding node, with children compared in order. Two empty trees are identical. An empty tree and a non-empty tree are not.
Return value
Return a dictionary with exactly these keys:
{
"components": int,
"min_swaps": int,
"largest_monotonic": int,
"cache_results": list,
"trees_identical": bool
}
Constraints
0 <= vertex_count <= 10^5, and the total number of edges is at most2 * 10^5.0 <= len(values) <= 10^5, and all values are distinct.0 <= limit <= 10^18.0 <= capacity <= 10^5, and0 <= len(operations) <= 10^5.- Operation names are always
"get"or"put". - Trees may be deep, so prefer iterative traversals over recursion.
- Aim for near-linear time on the graph and tree parts, O(1) per cache operation, and O(n log n) for the swap count.
Examples
Example 1
Input: analyze_bundle(5, {'0': [1], '1': [0, 2], '2': [1], '3': [4], '4': [3]}, [4, 3, 2, 1], 332, 2, [['put', 1, 10], ['put', 2, 20], ['get', 1], ['put', 3, 30], ['get', 2], ['get', 3]], {'val': 1, 'children': [{'val': 2, 'children': []}]}, {'val': 1, 'children': [{'val': 2, 'children': []}]})
Output: {'components': 2, 'min_swaps': 2, 'largest_monotonic': 299, 'cache_results': [None, None, 10, None, -1, 30], 'trees_identical': True}
Example 2
Input: analyze_bundle(3, {}, [], 0, 1, [], None, None)
Output: {'components': 3, 'min_swaps': 0, 'largest_monotonic': 0, 'cache_results': [], 'trees_identical': True}
Hints
Hint 1
For components, loop over every vertex label, and each time you reach an unvisited one, count a component and flood-fill from it with an explicit stack. Use `adjacency.get(str(v), [])` to look up neighbours.
Hint 2
For minimum swaps, map each value to its index in the sorted list. This gives a permutation of positions, and a cycle of length k needs k - 1 swaps.
Hint 3
For the monotonic number, scan digits right to left. When a digit is smaller than the one before it, decrement the earlier digit and remember that every digit after it becomes 9. For the cache, an ordered dictionary with move-to-end gives O(1) recency updates. For trees, compare node pairs with a stack and check values and child counts.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The five parts are independent, so each is solved on its own and the results are combined into one dictionary.
1. Connected components
Loop over every label from 0 to vertex_count - 1. When a vertex has not been visited, count a new component and flood-fill from it with an iterative DFS. Each fill covers exactly one component, so none is counted twice. Looping over all labels means isolated vertices, including those absent from adjacency, are counted too.
- Time: O(V + E)
- Space: O(V)
2. Minimum swaps to sort
Sort a copy of values and record each value's target index. Following i -> target(values[i]) gives a permutation, which splits into disjoint cycles.
- A cycle of length k can be fixed with k - 1 swaps.
- A single swap changes the number of cycles by at most one, and the sorted arrangement has n cycles. So at least n - (cycles) swaps are needed.
The answer is the sum of (k - 1) over all cycles.
- Time: O(n log n)
- Space: O(n)
3. Largest monotonic number
Scan the digits right to left. Whenever a digit is smaller than its left neighbour, decrement the left neighbour and remember that position. Scanning right to left lets a decrement that creates a new violation further left be fixed on the next step. After the scan, every digit after the leftmost decremented position becomes 9. That is the largest possible suffix, and it is non-decreasing. Converting back with int removes any leading zero, for example 10 gives 9.
- Time: O(d), where d is the number of digits
- Space: O(d)
4. LRU cache
An OrderedDict keeps keys in recency order.
getcallsmove_to_endon a hit and returns the value, or-1on a miss.putupdates the value and refreshes recency, then evicts from the front if the size exceedscapacity.- With capacity
0,putstores nothing.
Each operation is O(1) on average, and space is O(capacity).
5. Tree equality
Use a stack of node pairs. For each pair, check that both are present or both are absent, that the values match, and that the child counts match. Then push the corresponding child pairs. Any mismatch returns False. An explicit stack avoids recursion limits on deep trees.
- Time: O(N)
- Space: O(N) in the worst case
Reference solution
from typing import Dict, List, Optional
from collections import OrderedDict
def analyze_bundle(vertex_count: int, adjacency: Dict[str, List[int]], values: List[int], limit: int, capacity: int, operations: List[List], tree_a: Optional[Dict], tree_b: Optional[Dict]) -> Dict:
# 1. Connected components via iterative DFS.
seen = set()
components = 0
for start in range(vertex_count):
if start in seen:
continue
components += 1
seen.add(start)
stack = [start]
while stack:
vertex = stack.pop()
for neighbor in adjacency.get(str(vertex), adjacency.get(vertex, [])):
if neighbor not in seen:
seen.add(neighbor)
stack.append(neighbor)
# 2. Minimum swaps: n minus number of cycles in the sorting permutation.
position = {value: i for i, value in enumerate(sorted(values))}
visited = [False] * len(values)
swaps = 0
for i in range(len(values)):
if visited[i] or position[values[i]] == i:
continue
length = 0
j = i
while not visited[j]:
visited[j] = True
j = position[values[j]]
length += 1
swaps += length - 1
# 3. Largest number <= limit with non-decreasing digits.
digits = list(str(limit))
marker = len(digits)
for i in range(len(digits) - 1, 0, -1):
if digits[i] < digits[i - 1]:
marker = i - 1
digits[i - 1] = str(int(digits[i - 1]) - 1)
for i in range(marker + 1, len(digits)):
digits[i] = '9'
monotonic = int(''.join(digits))
# 4. LRU cache simulation.
cache = OrderedDict()
cache_results = []
for operation in operations:
name = operation[0].lower()
if name == 'get':
key = operation[1]
if key not in cache:
cache_results.append(-1)
else:
cache.move_to_end(key)
cache_results.append(cache[key])
elif name == 'put':
key, value = operation[1], operation[2]
if capacity > 0:
if key in cache:
cache.move_to_end(key)
cache[key] = value
if len(cache) > capacity:
cache.popitem(last=False)
cache_results.append(None)
else:
raise ValueError('operation must be get or put')
# 5. Tree equality, iteratively.
def identical(a, b):
stack = [(a, b)]
while stack:
left, right = stack.pop()
if left is None or right is None:
if left is not right:
return False
continue
if left['val'] != right['val']:
return False
left_children = left.get('children', [])
right_children = right.get('children', [])
if len(left_children) != len(right_children):
return False
stack.extend(zip(left_children, right_children))
return True
return {
'components': components,
'min_swaps': swaps,
'largest_monotonic': monotonic,
'cache_results': cache_results,
'trees_identical': identical(tree_a, tree_b),
}