Sort a List and Replay Commands on a Binary Search Tree
Trees & GraphsAuto-graded · 25 test casesLast updated
Sort an integer list without built-in sorting, then run a script of insert, search, delete and in-order commands on a duplicate-free binary search tree built from scratch.
Write a single function that does two independent jobs.
Job 1: sorting. Given a list of integers values, produce a new list containing the same numbers in non-decreasing order. Implement the sorting algorithm yourself (a quicksort variant is the natural choice). Do not use sorted, list.sort, or any library sorting routine. The input list must not be modified.
Job 2: tree commands. Start with an empty binary search tree of integer keys. Process the commands in order. Command i has the name operations[i] and its integer parameters are in arguments[i]. Implement the tree yourself, without any library tree or ordered-container type.
| Command | Parameters | Effect | Recorded result |
|---|---|---|---|
"insert" | [key] | Add key to the tree. If key is already present, the tree is left unchanged (no duplicates are stored). | None |
"search" | [key] | Check whether key is in the tree. | True or False |
"delete" | [key] | Remove key if present. If it is absent, nothing happens. | None |
"inorder" | [] | Read the keys in left-subtree, node, right-subtree order. | A new list of all keys in ascending order (an empty list if the tree is empty) |
When deleting a node with two children, replace its key with the smallest key of its right subtree and then remove that smallest node from the right subtree. This choice does not change what search or inorder return, but it is the standard approach.
The tree is entirely separate from values: the values being sorted are not inserted into the tree.
Return value. A dictionary with two entries:
"sorted": the sorted copy ofvalues"results": a list with one recorded result per command, in the same order as the commands. It is empty when there are no commands.
operations and arguments always have the same length.
Constraints
0 <= len(values) <= 10^50 <= len(operations) == len(arguments) <= 10^4- All numbers are integers that fit in a 64-bit signed integer;
valuesmay contain duplicates and may already be sorted or reverse sorted. - Every command name is one of
"insert","search","delete","inorder". arguments[i]has exactly one integer forinsert,searchanddelete, and is empty forinorder.- Your sorting should stay efficient on sorted input and on inputs with many equal values.
- Keep recursion in mind: a very lopsided tree or partition can be deep, so avoid unbounded stack growth where you can.
Examples
Example 1
Input: sort_and_run_bst_commands([3, 6, 8, 10, 1, 2, 1], [], [])
Output: {'sorted': [1, 1, 2, 3, 6, 8, 10], 'results': []}
Example 2
Input: sort_and_run_bst_commands([5, 3, 7, 2, 4, 6, 8], [], [])
Output: {'sorted': [2, 3, 4, 5, 6, 7, 8], 'results': []}
Example 3
Input: sort_and_run_bst_commands([4, 2, 6, 1, 3, 5, 7], [], [])
Output: {'sorted': [1, 2, 3, 4, 5, 6, 7], 'results': []}
Hints
Hint 1
For sorting, pick the middle element as the pivot and split the range into three zones: smaller than, equal to, and greater than the pivot. Equal elements are then never revisited, so many duplicates stay fast.
Hint 2
To keep the stack shallow, recurse into the smaller of the two outer zones and loop on the larger one.
Hint 3
For tree deletion handle three cases: no left child (return the right child), no right child (return the left child), and two children (copy the smallest key from the right subtree into this node, then delete that key from the right subtree).
Hint 4
Make insert and delete return the possibly new subtree root so the parent can reassign its child pointer; this also handles deleting the root of the whole tree.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two jobs are independent, so the function solves each separately and combines the answers in a dictionary.
Sorting: three-way quicksort
- Copy the input so the caller's list is untouched.
- For a range
[lo, hi], take the middle element as the pivot. Choosing the middle makes already-sorted and reverse-sorted inputs split evenly. - Sweep once with three pointers, maintaining this invariant:
a[lo:lt]is strictly less than the pivot,a[lt:i]equals the pivot,a[i:gt+1]is not yet examined,a[gt+1:hi+1]is strictly greater than the pivot.
- When the sweep ends (
i > gt), the middle zone equals the pivot and is already in its final place. Only the smaller-than and greater-than zones remain. - Recurse into the smaller of those two zones and loop on the larger. Each recursive call handles at most half the elements of the current range, so the stack depth is O(log n).
Equal keys are grouped in the middle zone and never revisited, so inputs with many duplicates do not degrade.
Tree: recursive BST with returned subtree roots
- insert: go left for a smaller key, right for a larger one, and create a node at an empty spot. An equal key changes nothing.
- search: follow the same left/right path iteratively until the key is found or the path ends.
- delete: find the node. With no left child, return its right child. With no right child, return its left child. With two children, copy the minimum key of the right subtree (the in-order successor) into the node, then delete that key from the right subtree. Because each call returns the new subtree root, the parent relinks correctly, including when the root itself is deleted. A missing key is simply not found and nothing changes.
- inorder: left, node, right produces keys in ascending order thanks to the ordering invariant (everything in the left subtree is smaller, everything in the right is larger).
Why it is correct
The partition invariant guarantees that after each sweep the pivot-equal elements sit in their final positions, and the two outer zones contain exactly the elements that belong on each side, so induction on range size yields a fully sorted list. The BST invariant is preserved by every operation: insert adds a leaf on the unique valid path, and delete either splices out a node with at most one child or substitutes the successor, which is greater than everything in the left subtree and not greater than anything else in the right subtree.
Complexity
- Sorting: O(n log n) expected, O(n^2) worst case for adversarial pivot patterns, which the middle-pivot choice makes unlikely for sorted inputs. Extra space is O(n) for the copy plus O(log n) stack.
- Tree: each insert, search and delete costs O(h), where h is the tree height. h is O(log n) for random-like key orders but O(n) if keys are inserted in sorted order.
inordercosts O(m) for m keys currently stored. Space is O(m) for the nodes.
Reference solution
from typing import Dict, List
class _Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def sort_and_run_bst_commands(values, operations, arguments):
# Three-way partitioning keeps runs of equal keys from being re-processed.
def quicksort(src):
a = list(src)
def sort(lo, hi):
while lo < hi:
pivot = a[(lo + hi) // 2]
lt, i, gt = lo, lo, hi
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
# Recurse on the smaller side, loop on the larger one: depth O(log n).
if lt - lo < hi - gt:
sort(lo, lt - 1)
lo = gt + 1
else:
sort(gt + 1, hi)
hi = lt - 1
sort(0, len(a) - 1)
return a
root = None
def insert(node, key):
if node is None:
return _Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def contains(node, key):
while node is not None:
if key == node.key:
return True
node = node.left if key < node.key else node.right
return False
def remove(node, key):
if node is None:
return None
if key < node.key:
node.left = remove(node.left, key)
elif key > node.key:
node.right = remove(node.right, key)
else:
if node.left is None:
return node.right
if node.right is None:
return node.left
successor = node.right
while successor.left is not None:
successor = successor.left
node.key = successor.key
node.right = remove(node.right, successor.key)
return node
def inorder(node, out):
if node is not None:
inorder(node.left, out)
out.append(node.key)
inorder(node.right, out)
results = []
for operation, args in zip(operations, arguments):
if operation == "insert":
root = insert(root, args[0])
results.append(None)
elif operation == "search":
results.append(contains(root, args[0]))
elif operation == "delete":
root = remove(root, args[0])
results.append(None)
elif operation == "inorder":
traversal = []
inorder(root, traversal)
results.append(traversal)
else:
raise ValueError("unknown operation")
return {"sorted": quicksort(values), "results": results}