Convert Sorted Array to Balanced BST in DSA C# - Time & Space Complexity
We want to understand how the time needed to build a balanced binary search tree changes as the input array grows.
How does the number of steps grow when the array size increases?
Analyze the time complexity of the following code snippet.
public TreeNode SortedArrayToBST(int[] nums, int left, int right) {
if (left > right) return null;
int mid = left + (right - left) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = SortedArrayToBST(nums, left, mid - 1);
node.right = SortedArrayToBST(nums, mid + 1, right);
return node;
}
This code builds a balanced binary search tree by choosing the middle element as root and recursively doing the same for left and right halves.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls splitting the array and creating nodes.
- How many times: Each element is visited once to create a node, so total calls equal the number of elements.
Each element leads to one node creation and two recursive calls on smaller parts.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 node creations and recursive calls |
| 100 | About 100 node creations and recursive calls |
| 1000 | About 1000 node creations and recursive calls |
Pattern observation: The number of operations grows roughly in direct proportion to the input size.
Time Complexity: O(n)
This means the time to build the tree grows linearly with the number of elements in the array.
[X] Wrong: "Because the function calls itself twice, the time complexity is exponential like O(2^n)."
[OK] Correct: Each element is processed only once to create a node, so the total work is proportional to n, not exponential.
Understanding this helps you explain how recursion can efficiently build balanced trees, a common skill in coding interviews.
"What if we changed the input from a sorted array to an unsorted array? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem goal
The goal is to convert a sorted array into a BST that is balanced, meaning the tree height is minimized.Step 2: Reason about balanced BST
A balanced BST has roughly equal nodes on left and right subtrees, minimizing height and improving search efficiency.Final Answer:
To create a BST with minimum height -> Option AQuick Check:
Balanced BST = minimum height [OK]
- Confusing balanced BST with sorted linked list
- Thinking the array needs to be reversed
- Assuming sorting again is required
Solution
Step 1: Identify base case condition
When start index is greater than end index, it means no elements remain to form a node, so return null.Step 2: Match correct syntax
The correct syntax is "if (start > end) return null;" which stops recursion properly.Final Answer:
if (start > end) return null; -> Option CQuick Check:
Base case = start > end returns null [OK]
- Using start == end as base case incorrectly
- Returning new node instead of null in base case
- Using wrong comparison operators
TreeNode SortedArrayToBST(int[] nums, int start, int end) {
if (start > end) return null;
int mid = (start + end) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = SortedArrayToBST(nums, start, mid - 1);
node.right = SortedArrayToBST(nums, mid + 1, end);
return node;
}
var root = SortedArrayToBST(new int[] {1, 2, 3, 4, 5}, 0, 4);
PrintInorder(root);Solution
Step 1: Understand inorder traversal
Inorder traversal of BST visits left subtree, root, then right subtree, producing sorted order.Step 2: Trace the code output
The code builds a balanced BST from sorted array, so inorder traversal outputs original sorted array: 1, 2, 3, 4, 5.Final Answer:
1 -> 2 -> 3 -> 4 -> 5 -> null -> Option DQuick Check:
Inorder traversal = sorted array [OK]
- Confusing preorder or postorder with inorder
- Assuming output is reversed
- Misunderstanding recursion mid calculation
TreeNode SortedArrayToBST(int[] nums, int start, int end) {
if (start >= end) return null;
int mid = (start + end) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = SortedArrayToBST(nums, start, mid - 1);
node.right = SortedArrayToBST(nums, mid + 1, end);
return node;
}Solution
Step 1: Analyze base case condition
The base case incorrectly returns null when start == end, skipping valid single element nodes.Step 2: Correct base case condition
It should return null only when start > end, allowing nodes when start == end.Final Answer:
Base case condition should be start > end, not start >= end -> Option AQuick Check:
Base case = start > end returns null [OK]
- Using >= instead of > in base case
- Changing mid calculation unnecessarily
- Incorrect subtree index ranges
Solution
Step 1: Understand BST property with duplicates
BST requires left subtree values less than root, right subtree values greater or equal to root for duplicates.Step 2: Decide duplicate placement
Placing duplicates consistently in the right subtree maintains BST property and balanced structure.Final Answer:
Place duplicates consistently in the right subtree -> Option BQuick Check:
Duplicates go right subtree to keep BST valid [OK]
- Placing duplicates randomly breaking BST rules
- Ignoring duplicates causing data loss
- Placing duplicates in left subtree breaking order
Ready to prove it?
Pass the test and this pattern moves unknown
