Kth Smallest Element in BST in DSA Typescript - Time & Space Complexity
We want to know how long it takes to find the kth smallest value in a Binary Search Tree (BST).
This helps us understand how the search time grows as the tree or k grows.
Analyze the time complexity of the following code snippet.
function kthSmallest(root: TreeNode | null, k: number): number {
let count = 0;
let result = -1;
function inorder(node: TreeNode | null) {
if (!node || result !== -1) return;
inorder(node.left);
count++;
if (count === k) {
result = node.val;
return;
}
inorder(node.right);
}
inorder(root);
return result;
}
This code does an in-order traversal of the BST to find the kth smallest element.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive in-order traversal visiting nodes.
- How many times: Visits nodes until the kth smallest is found, up to k times in best case, up to n times in worst case.
As the tree size (n) grows, the number of nodes visited depends on k and tree shape.
| Input Size (n) | Approx. Operations (nodes visited) |
|---|---|
| 10 | Up to 10 (if k=10), or fewer if k smaller |
| 100 | Up to 100 (if k=100), or fewer if k smaller |
| 1000 | Up to 1000 (if k=1000), or fewer if k smaller |
Pattern observation: The work grows roughly with k, but cannot exceed n (total nodes).
Time Complexity: O(h + k)
This means the time depends on the tree height (h) plus how many nodes we visit until kth smallest.
[X] Wrong: "The time is always O(n) because we might visit all nodes."
[OK] Correct: Actually, we stop once we find the kth smallest, so if k is small, we visit fewer nodes, making it faster than visiting all.
Understanding this time complexity shows you can analyze recursive tree traversals and how stopping early affects performance.
"What if the BST is balanced vs completely skewed? How would the time complexity change?"
Practice
Solution
Step 1: Understand the BST property
A Binary Search Tree (BST) stores values so that left child nodes are smaller and right child nodes are larger than the parent.Step 2: Define the Kth smallest element
The Kth smallest element is the element that would appear in position K if all elements were sorted in ascending order.Final Answer:
The element that is the Kth smallest value in the Binary Search Tree -> Option AQuick Check:
Kth smallest means sorted order position K [OK]
- Confusing Kth smallest with largest element
- Thinking it means tree height
- Counting nodes instead of values
Solution
Step 1: Check parameter types and order
The function should take the root node (which can be null) and a number k representing the position.Step 2: Check return type
The function returns the value (number) of the Kth smallest element, not a node or void.Final Answer:
function kthSmallest(root: TreeNode | null, k: number): number -> Option BQuick Check:
Correct parameter types and return number [OK]
- Swapping parameter order
- Using wrong return type
- Using string instead of number for k
kthSmallest(root, 3)?BST structure:
5
/ \
3 7
/ \ \
2 4 8
Solution
Step 1: Perform in-order traversal
In-order traversal visits nodes in ascending order: 2, 3, 4, 5, 7, 8.Step 2: Identify the 3rd element
The 3rd element in this order is 4.Final Answer:
4 -> Option CQuick Check:
In-order 3rd element = 4 [OK]
- Counting root as first without traversal
- Confusing left and right subtree order
- Picking value by node depth
function kthSmallest(root: TreeNode | null, k: number): number {
let count = 0;
let result = -1;
function inorder(node: TreeNode | null) {
if (!node) return;
inorder(node.left);
count++;
if (count === k) {
result = node.val;
return;
}
inorder(node.right);
}
inorder(root);
return result;
}What is the main problem with this code?
Solution
Step 1: Analyze traversal stopping condition
The code sets result when count equals k but does not stop further recursion, so it continues traversing unnecessarily.Step 2: Understand impact of not stopping traversal
Without stopping, the function wastes time and may overwrite result if not careful.Final Answer:
The function does not stop traversal after finding the Kth element -> Option AQuick Check:
Traversal must stop after Kth element found [OK]
- Assuming return stops all recursion
- Not using a flag to stop traversal
- Ignoring null root case
Solution
Step 1: Consider repeated queries
Performing in-order traversal each time is costly for large trees and many queries.Step 2: Use pre-processing for efficiency
Storing the sorted elements from one in-order traversal allows O(1) access for each Kth smallest query.Step 3: Evaluate other options
Breadth-first search does not give sorted order; random picking is inefficient and unreliable.Final Answer:
Store the in-order traversal result in an array once, then answer queries by indexing -> Option DQuick Check:
Precompute once, query fast [OK]
- Recomputing traversal for each query
- Using BFS which is unsorted
- Random selection guessing
Ready to prove it?
Pass the test and this pattern moves unknown
