KatInterview

Five-Task Toolkit: Graphs, Swaps, Digits, Cache, Trees

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphsgraph-traversalcycle-decompositiongreedy-digits

Last 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, labelled 0 to vertex_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 either None (empty) or a dictionary {"val": x, "children": [subtree, ...]}. A missing "children" entry means no children.

The five sub-tasks

  1. Connected components. Count the connected components of the graph. Isolated vertices, including those missing from adjacency, each count as one component. If vertex_count is 0, the answer is 0.
  2. Minimum swaps to sort. Find the minimum number of swaps of two elements (at any positions) needed to arrange values in ascending order. An empty or already sorted list needs 0.
  3. Largest monotonic number. Find the largest integer that is less than or equal to limit and whose decimal digits are in non-decreasing order from left to right. For example, 332 gives 299, and 10 gives 9.
  4. LRU cache simulation. Start with an empty cache of the given capacity and process operations in order.
    • get returns the stored value and marks that key as most recently used. If the key is absent, it returns -1.
    • put stores or overwrites the value and marks the key as most recently used. If the cache then holds more than capacity keys, remove the least recently used key.
    • If capacity is 0, put stores nothing.
    • Record one result per operation: the returned value for get, and None for put.
  5. Tree equality. Decide whether tree_a and tree_b are identical. They are identical when they have the same shape and equal val at 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 most 2 * 10^5.
  • 0 <= len(values) <= 10^5, and all values are distinct.
  • 0 <= limit <= 10^18.
  • 0 <= capacity <= 10^5, and 0 <= 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.