Design an AVL tree with insert, delete and kth-smallest queries
Company: AMD
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: hard
Interview Round: Other
Design a self-balancing binary search tree, specifically an AVL tree, that can take a large stream of values while keeping search fast. The tree must rebalance itself after every insertion and deletion so that its height stays `O(log n)` and lookups run in `O(log n)` time.
The structure supports the standard BST operations (insertion, deletion and search). It also returns the minimum and maximum values, answers kth smallest queries, produces an in-order traversal, and reports the current height and size of the tree.
Duplicate values are ignored on insertion. If a deletion target does not exist, the operation indicates failure. The tree must stay balanced at all times.
Implement the following methods:
- `insert(val: int)`: insert a value. Duplicates are ignored. The tree rebalances automatically.
- `delete(val: int) -> bool`: delete a value. Return `True` if the value was found and deleted, `False` otherwise.
- `search(val: int) -> bool`: return `True` if the value is in the tree, `False` otherwise.
- `getMin() -> int`: return the minimum value, or -1 if the tree is empty.
- `getMax() -> int`: return the maximum value, or -1 if the tree is empty.
- `getKthSmallest(k: int) -> int`: return the kth smallest element (1-indexed), or -1 if `k` is out of range.
- `getInorder() -> List[int]`: return all elements in sorted (in-order) order as a list.
- `getHeight() -> int`: return the height of the tree. An empty tree has height 0 and a single node has height 1.
- `getSize() -> int`: return the number of elements currently in the tree.
Example 1 builds a tree that needs single and double rotations, then deletes two values:
```text
Input:
["SelfBalancingBST", "insert", "insert", "insert", "insert", "insert", "insert", "insert", "getSize", "getHeight", "getInorder", "getKthSmallest", "getKthSmallest", "search", "delete", "delete", "getHeight", "getInorder"]
[[], [10], [20], [30], [40], [50], [25], [20], [], [], [], [4], [7], [35], [50], [40], [], []]
Output: [null, null, null, null, null, null, null, null, 6, 3, [10, 20, 25, 30, 40, 50], 30, -1, false, true, true, 3, [10, 20, 25, 30]]
Explanation:
bst = SelfBalancingBST()
bst.insert(10) # tree: 10
bst.insert(20) # 10 with right child 20
bst.insert(30) # right-right case at 10, left rotation: 20 is the root
bst.insert(40) # 30 gets right child 40, still balanced
bst.insert(50) # right-right case at 30, left rotation: 40 takes its place
bst.insert(25) # right-left case at the root, 30 becomes the root:
# 30 -> left 20 (children 10, 25), right 40 (right child 50)
bst.insert(20) # duplicate, ignored
bst.getSize() # -> 6
bst.getHeight() # -> 3
bst.getInorder() # -> [10, 20, 25, 30, 40, 50]
bst.getKthSmallest(4) # -> 30 (the root's left subtree holds 3 values)
bst.getKthSmallest(7) # -> -1 (only 6 values stored)
bst.search(35) # -> False
bst.delete(50) # -> True
bst.delete(40) # -> True; root 30 is now left-heavy by 2 and its left child
# 20 has balance 0, so one right rotation makes 20 the root
bst.getHeight() # -> 3 (20 -> left 10, right 30 with left child 25)
bst.getInorder() # -> [10, 20, 25, 30]
```
Example 2 covers the empty tree and a delete of a missing value:
```text
Input:
["SelfBalancingBST", "getMin", "getMax", "getSize", "insert", "insert", "insert", "delete", "delete", "getInorder", "getKthSmallest"]
[[], [], [], [], [1], [2], [3], [5], [2], [], [2]]
Output: [null, -1, -1, 0, null, null, null, false, true, [1, 3], 3]
Explanation:
bst = SelfBalancingBST() # empty AVL tree
bst.getMin() # -> -1 (tree is empty)
bst.getMax() # -> -1 (tree is empty)
bst.getSize() # -> 0
bst.insert(1) # tree: [1]
bst.insert(2) # tree: [1, 2]
bst.insert(3) # triggers a rebalance, tree: [1, 2, 3]
bst.delete(5) # -> False (5 is not in the tree)
bst.delete(2) # -> True (2 removed)
bst.getInorder() # -> [1, 3]
bst.getKthSmallest(2) # -> 3 (2nd smallest of [1, 3])
```
```hint What each node should remember
Height alone is enough to rebalance. Think about which extra per-node count would let you skip a whole subtree when you look for the kth value, and which operations must keep that count current.
```
```hint Deletion has an extra case
After a deletion, the child on the heavy side can have a balance factor of 0, which never happens after an insertion. Work out which rotation fixes that case before you write the condition.
```
```hint Reporting a delete
When the matched node has two children, it stays in place and only its value changes. Choose a way for `delete` to tell whether anything was removed that does not depend on which node object disappeared.
```
### Constraints & Assumptions
- `-10⁹ <= val <= 10⁹`
- At most `10⁵` total calls will be made.
- For `getKthSmallest`, valid `k` satisfies `1 <= k <= size`. Return -1 when `k` is out of range.
- `getMin` and `getMax` return -1 if the tree is empty.
- Duplicate values are ignored on insertion.
### Clarifying Questions to Ask
- -1 is a legal stored value, so `getMin` returning -1 is ambiguous on a tree that contains -1. Is the sentinel required, or may the method return `None` or raise on an empty tree?
- Will the tree be read and written from more than one thread at the same time?
- For a very large tree, is building a full list in `getInorder` acceptable, or would a lazy iterator be preferred?
### What a Strong Answer Covers
- The node fields (value, children, height, subtree size) and when height and size are recomputed, including inside rotations.
- All four imbalance cases and the exact test that chooses a single or a double rotation, including the balance-0 child that only deletion produces.
- Deletion of a node with zero, one or two children, rebalancing every ancestor on the way back up, and a correct `True`/`False` result.
- The kth smallest walk using subtree sizes, with out-of-range `k` and the empty tree handled.
- The time and space cost of each method, and why the AVL height bound makes the point operations `O(log n)`.
### Follow-up Questions
- How would you change the API so a caller can tell an empty tree apart from a stored -1?
- How would you add `rank(val)`, the number of stored values smaller than `val`, in `O(log n)`?
- For a write-heavy stream, would you choose an AVL tree, a red-black tree or a skip list, and why?
- How would you let many readers query the tree while one writer keeps inserting?
Overview: Implement an AVL tree that supports insert, delete, search, min, max, kth smallest, in-order traversal, height and size queries. It tests the four rotation cases, rebalancing after deletion, and storing a subtree size in each node so rank queries run in O(log n).