The O(n) solution clicked for me pretty quickly once I thought about what preorder actually guarantees.
Use a stack to simulate the preorder traversal while maintaining a lower bound for each node. Iterate through the array, and when a value exceeds the current lower bound, pop from the stack until the top is greater than the value, updating the lower bound to the last popped value. If any value is less than the lower bound, the sequence is invalid.
Pro tip: Clarify that the BST is strictly binary (no duplicates) and mention that the stack approach runs in O(n) time and O(n) space, which is optimal. Also, briefly explain why the lower bound works: it represents the minimum allowed value for the next node in the right subtree of the last popped node.
Restate the problem: given a preorder sequence, determine if it can be the preorder traversal of a BST. Clarify assumptions about duplicates (usually none).
Explain that a stack can simulate the traversal, and a lower bound tracks the minimum allowed value for the next node. This avoids building the tree explicitly.
Iterate through the array: if the current value is less than the lower bound, return false. While the stack is not empty and the current value is greater than the top, pop and update the lower bound to the popped value. Push the current value onto the stack.
State that time complexity is O(n) and space is O(n). Discuss edge cases: empty array, single element, sorted ascending/descending, and duplicates if allowed.
Validate the algorithm with examples: [5,2,1,3,6] is valid; [5,2,6,1,3] is invalid because 1 < lower bound after popping 5 and 6.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.