BST In-Order Traversal Flow & Priority Queue Dispatcher
Data Structure DesignModel answerLast updated
Implement an in-order tree iterator with memory constrained by height, followed by a priority queue that handles multi-attribute ordering rules.
This design challenge consists of two distinct components.
Part 1: Binary Search Tree Step Iterator
Implement a step-by-step iterator over a Binary Search Tree (BST) that processes nodes in ascending numerical order (in-order traversal).
Define a class BSTIterator with the following contract:
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
pass
def next(self) -> int:
pass
def hasNext(self) -> bool:
pass
Requirements:
next()fetches the next smallest value remaining in the BST.hasNext()returnsTrueif further unvisited nodes remain, otherwiseFalse.- Memory Constraint: Auxiliary space must remain $O(h)$, where $h$ is the height of the tree.
- Time Constraint:
hasNext()must run in $O(1)$ time.next()must operate in $O(1)$ amortized time.
Part 2: Priority-Based Customer Ticket Dispatcher
Design an event-dispatching queue for customer support requests. Every incoming ticket is represented by (urgency_level, creation_time, ticket_id).
Implement a class TicketDispatcher with the following methods:
submit_ticket(urgency_level: int, creation_time: int, ticket_id: str): Enqueues a new ticket.dispatch_next(): Pops and returns theticket_idof the ticket with the highest priority according to these rules:- Higher
urgency_leveltakes precedence (e.g., urgency 5 comes before urgency 1). - For equal
urgency_level, smallercreation_timetakes precedence (earlier requests first). - For equal
urgency_levelandcreation_time, smallerticket_idtakes precedence (lexicographical comparison).
- Higher
If no tickets are present, dispatch_next() should return None.
Example:
dispatcher = TicketDispatcher()
dispatcher.submit_ticket(1, 1200, "T-101")
dispatcher.submit_ticket(3, 1100, "T-102")
dispatcher.submit_ticket(3, 1100, "T-100")
dispatcher.dispatch_next() # Returns "T-100" (urgency 3, time 1100, ID "T-100" < "T-102")
dispatcher.dispatch_next() # Returns "T-102"
dispatcher.dispatch_next() # Returns "T-101"
dispatcher.dispatch_next() # Returns None
Hints
Hint 1
For Part 1, simulating the call stack requires holding left descendants. Think about when you need to push a node's right child subtree.
Hint 2
For Part 2, Python's min-heap sorts tuples element-by-element. How can you transform values so min-heap semantics match your max/min ordering criteria?
Hint 3
Consider edge cases: empty root tree in Part 1, or dispatch calls on an empty queue in Part 2.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Component 1: BST In-Order Iterator
Problem Analysis & Strategy
An in-order traversal of a Binary Search Tree produces sorted values. While flattening the whole tree into a list via full traversal uses $O(n)$ space, the requirement specifies $O(h)$ auxiliary memory, where $h$ is the tree height.
To achieve $O(h)$ space, we simulate recursive in-order traversal using an explicit stack that only stores the active ancestor path.
- Initialization: Starting at the root node, traverse down the left subtree, pushing every node visited onto the stack. The top of the stack will be the absolute minimum element in the subtree.
next(): Pop the top node from the stack. Its value is the next in-order result. Before returning, if this node possesses a right child, traverse that right child's left-most branch, pushing all traversed nodes onto the stack.hasNext(): Simply check if the stack contains any nodes.
Complexity Analysis
hasNext()Time Complexity: $O(1)$ worst-case.next()Time Complexity: $O(1)$ amortized. Each tree node is pushed to and popped from the stack exactly once across all iterations.- Space Complexity: $O(h)$, where $h$ is the height of the BST. The stack depth never exceeds the tree height.
Component 2: Priority-Based Ticket Dispatcher
Problem Analysis & Strategy
We need to serve items sorted by three distinct criteria:
urgency_level(descending / max priority)creation_time(ascending / min priority)ticket_id(ascending / min lexicographical)
Standard min-heaps evaluate tuples sequentially element-by-element. By storing tuple keys in the form: $$(- \text{urgency_level}, \text{creation_time}, \text{ticket_id})$$
The min-heap will naturally pop tickets with the highest urgency_level first (since a larger positive number becomes smaller when negated). Ties are then resolved by smaller creation_time and finally smaller ticket_id.
Complexity Analysis
submit_ticket()Time Complexity: $O(\log n)$ to push into the min-heap.dispatch_next()Time Complexity: $O(\log n)$ to pop the top element.- Space Complexity: $O(n)$ where $n$ is the total active tickets stored in memory.
Executable Python Implementation
from typing import Optional, List
import heapq
class TreeNode:
def __init__(self, val: int = 0, left: 'Optional[TreeNode]' = None, right: 'Optional[TreeNode]' = None):
self.val = val
self.left = left
self.right = right
class BSTIterator:
"""
In-order BST iterator with O(h) space and amortized O(1) time complexity.
"""
def __init__(self, root: Optional[TreeNode]):
self.stack: List[TreeNode] = []
self._push_left_path(root)
def _push_left_path(self, node: Optional[TreeNode]) -> None:
while node is not None:
self.stack.append(node)
node = node.left
def next(self) -> int:
if not self.hasNext():
raise IndexError("next() called on empty iterator")
curr = self.stack.pop()
if curr.right is not None:
self._push_left_path(curr.right)
return curr.val
def hasNext(self) -> bool:
return len(self.stack) > 0
class TicketDispatcher:
"""
Priority-queue dispatcher managing tickets by urgency, time, and ID.
"""
def __init__(self):
self._pq = []
def submit_ticket(self, urgency_level: int, creation_time: int, ticket_id: str) -> None:
# Tuple key: (-urgency_level, creation_time, ticket_id)
# Reverses urgency direction for min-heap implementation.
heapq.heappush(self._pq, (-urgency_level, creation_time, ticket_id))
def dispatch_next(self) -> Optional[str]:
if not self._pq:
return None
_, _, ticket_id = heapq.heappop(self._pq)
return ticket_id
Edge Cases & Design Trade-Offs
- Empty / Null Trees: If the BST
rootisNone, the initial stack is empty, causinghasNext()to correctly returnFalse. - Empty Priority Queue: Invoking
dispatch_next()on an empty dispatcher returnsNonesafely without index errors. - Concurrency: In a multi-threaded execution context, the heap state in
TicketDispatchercan experience race conditions. A real-world production system would protect_pqusing an explicit reentrant lock (threading.Lock), or swap the underlying heap with thread-safe queues such asqueue.PriorityQueue.