Challenge - 5 Problems
BST Iterator Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of BST Iterator next() calls
Given a BST Iterator initialized with the BST below, what is the output sequence of calling next() three times?
DSA C
/* BST structure: 7 / \ 3 15 / \ 9 20 */ BSTIterator iterator = BSTIterator_create(root); int a = BSTIterator_next(iterator); int b = BSTIterator_next(iterator); int c = BSTIterator_next(iterator); printf("%d %d %d", a, b, c);
Attempts:
2 left
💡 Hint
Remember that BST Iterator returns elements in ascending order.
✗ Incorrect
The BST Iterator returns the next smallest element each time next() is called. The in-order traversal of the BST is 3, 7, 9, 15, 20. So the first three next() calls return 3, 7, and 9 respectively.
🧠 Conceptual
intermediateSpace complexity of BST Iterator
What is the worst-case space complexity of a BST Iterator that uses a stack to simulate in-order traversal on a BST with n nodes?
Attempts:
2 left
💡 Hint
Consider the shape of the BST and how many nodes can be on the stack at once.
✗ Incorrect
In the worst case, the BST is skewed (like a linked list), so the stack can hold all n nodes. Thus, the space complexity is O(n).
🔧 Debug
advancedIdentify the error in BST Iterator next() implementation
What error will this BST Iterator next() method cause when called on a non-empty BST?
DSA C
int BSTIterator_next(BSTIterator* iter) { TreeNode* node = stack_pop(iter->stack); if (node->right != NULL) { stack_push(iter->stack, node->right); } return node->val; }
Attempts:
2 left
💡 Hint
Think about how in-order traversal visits left children before the node and right subtree.
✗ Incorrect
The code pushes only the right child but does not push all left descendants of the right child. This breaks the in-order traversal order, causing incorrect output.
📝 Syntax
advancedSyntax error in BST Iterator initialization
Which option correctly initializes the stack with all left children of the root node in a BST Iterator constructor?
DSA C
void BSTIterator_init(BSTIterator* iter, TreeNode* root) {
while (root != NULL) {
// push root
root = root->left;
}
}Attempts:
2 left
💡 Hint
stack_push needs two arguments: the stack and the node pointer.
✗ Incorrect
Option C correctly pushes the current node pointer onto the stack and moves to the left child. Option C misses the node argument, causing a syntax error. Option C moves right instead of left, breaking logic. Option C pushes node value instead of node pointer, breaking stack usage.
🚀 Application
expertNumber of next() calls to exhaust BST Iterator
Given a BST with 10 nodes, how many times can you call next() before hasNext() returns false?
Attempts:
2 left
💡 Hint
Each next() call returns exactly one node value.
✗ Incorrect
The BST Iterator returns each node exactly once. For 10 nodes, next() can be called 10 times before no nodes remain.
