KatInterview

BST In-Order Traversal Flow & Priority Queue Dispatcher

Data Structure DesignModel answer

Last 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() returns True if further unvisited nodes remain, otherwise False.
  • 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 the ticket_id of the ticket with the highest priority according to these rules:
    1. Higher urgency_level takes precedence (e.g., urgency 5 comes before urgency 1).
    2. For equal urgency_level, smaller creation_time takes precedence (earlier requests first).
    3. For equal urgency_level and creation_time, smaller ticket_id takes precedence (lexicographical comparison).

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.