Practice
helper with input nums = [1, 3, 5]?Solution
Step 1: Calculate mid index for initial call
For nums=[1,3,5], left=0, right=2, mid=(0+2)//2=1.Step 2: Identify root value
nums[mid] = nums[1] = 3, so root node value is 3.Final Answer:
Option A -> Option AQuick Check:
Mid index calculation picks 3 as root [OK]
- Choosing first or last element as root
- Off-by-one mid calculation
Solution
Step 1: Understand the problem constraints
We want to find the kth smallest element in a BST efficiently, avoiding unnecessary traversal.Step 2: Evaluate approaches
Full inorder traversal (A) is correct but not optimal since it traverses the entire tree. Greedy left moves (C) fail because the kth element may not be in the leftmost path. DP (D) is complex and not standard for this problem. Iterative inorder with early stopping (B) visits only needed nodes, achieving O(H + k) time and O(H) space.Final Answer:
Option B -> Option BQuick Check:
Iterative inorder with early stopping avoids full traversal [OK]
- Assuming full traversal is necessary
- Confusing greedy left moves with inorder traversal
Solution
Step 1: Understand base case condition
The base case should be when left > right, not left >= right, to allow single-element subarrays.Step 2: Consequence of incorrect base case
Using left >= right causes the recursion to skip processing subarrays of size 1, leading to infinite recursion or missing nodes.Final Answer:
Option D -> Option DQuick Check:
Base case must allow left == right to process single elements [OK]
- Incorrect base case causing infinite recursion
- Misplaced mid calculation
def insertIntoBST(root, val):
if root is None:
return TreeNode(val)
curr = root
while curr:
if val < curr.val:
if curr.left is None:
curr.left = TreeNode(val)
return root
curr = curr.left
else:
if curr.right is None:
curr.right = TreeNode(val)
return root
curr = curr.right
return root
Solution
Step 1: Identify traversal cost
Insertion requires traversing from root down to a leaf where the new node is inserted.Step 2: Relate traversal to tree height
In worst case, the tree is skewed, so height h can be up to n, but complexity is expressed as O(h).Final Answer:
Option B -> Option BQuick Check:
Traversal cost dominates insertion -> O(h) [OK]
- Assuming O(1) because insertion is at leaf
- Confusing height h with number of nodes n
- Assuming BST is always balanced
Solution
Step 1: Analyze traversal steps
The algorithm traverses down to the leftmost node (cost O(H)) and then visits k nodes in inorder sequence.Step 2: Combine costs
Total time is O(H) to reach leftmost node plus O(k) to visit k nodes, so O(H + k).Final Answer:
Option A -> Option AQuick Check:
Traversal cost depends on height plus k nodes visited [OK]
- Assuming O(n) always
- Ignoring height cost
- Assuming only k nodes visited without stack overhead
