Convert Sorted Array to Balanced BST in DSA C - Time & Space Complexity
We want to know how the time needed to build a balanced binary search tree changes as the input array grows.
Specifically, how does the work increase when the sorted array gets bigger?
Analyze the time complexity of the following code snippet.
struct TreeNode {
int val;
struct TreeNode *left, *right;
};
struct TreeNode* sortedArrayToBST(int* nums, int left, int right) {
if (left > right) return NULL;
int mid = left + (right - left) / 2;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = nums[mid];
root->left = sortedArrayToBST(nums, left, mid - 1);
root->right = sortedArrayToBST(nums, mid + 1, right);
return root;
}
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 tree nodes.
- How many times: Each element is visited once to create a node, so total calls equal the number of elements.
Each element in the array leads to one node creation and recursive calls split the array in halves.
| 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 work 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 O(2^n)."
[OK] Correct: Each element is processed only once to create a node, so calls do not multiply exponentially but split the array into smaller parts.
Understanding this time complexity helps you explain how recursive tree building works efficiently and shows you can analyze divide-and-conquer algorithms clearly.
"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 for efficient operations.Step 2: Identify balanced BST property
A balanced BST has roughly equal nodes on left and right subtrees, minimizing height and ensuring faster search.Final Answer:
To create a BST with minimal height -> Option BQuick Check:
Balanced BST = minimal height [OK]
- Thinking the array needs to be reversed
- Confusing BST with linked list
- Ignoring the balance requirement
Solution
Step 1: Understand recursion base case
When start index is greater than end index, it means no elements remain to process, so return NULL (no node).Step 2: Check each option
if (start > end) return NULL; correctly checks if start > end to stop recursion. Other options do not correctly represent the base case.Final Answer:
if (start > end) return NULL; -> Option CQuick Check:
Base case = start > end [OK]
- Using start == end as base case incorrectly
- Returning NULL too early
- Confusing start and end indices
[1, 2, 3, 4, 5], what is the root value of the balanced BST created by the standard algorithm?Solution
Step 1: Find middle element of array
The middle element of [1, 2, 3, 4, 5] is at index 2 (0-based), which is 3.Step 2: Middle element becomes root
In balanced BST from sorted array, middle element is root to balance left and right subtrees.Final Answer:
3 -> Option AQuick Check:
Middle element = root = 3 [OK]
- Choosing first or last element as root
- Off-by-one error in middle index calculation
- Confusing array indices
TreeNode* sortedArrayToBST(int arr[], int start, int end) {
if (start >= end) return NULL;
int mid = (start + end) / 2;
TreeNode* root = new TreeNode(arr[mid]);
root->left = sortedArrayToBST(arr, start, mid - 1);
root->right = sortedArrayToBST(arr, mid + 1, end);
return root;
}Solution
Step 1: Analyze base case condition
The base case should stop recursion when start > end, because when start == end, there is still one element to process.Step 2: Check recursive calls
Left subtree uses start to mid-1, right subtree uses mid+1 to end, which is correct.Final Answer:
Base case condition should be start > end, not start >= end -> Option DQuick Check:
Base case = start > end [OK]
- Stopping recursion too early with start >= end
- Incorrect mid index calculation
- Wrong subtree index ranges
[2, 4, 6, 8, 10, 12, 14]. After converting it to a balanced BST, what is the inorder traversal of the BST?Solution
Step 1: Understand inorder traversal of BST
Inorder traversal of a BST always returns the sorted order of elements.Step 2: Check given array and traversal
The array is already sorted. After conversion to balanced BST, inorder traversal must return the same sorted array.Final Answer:
[2, 4, 6, 8, 10, 12, 14] -> Option AQuick Check:
Inorder traversal = sorted array [OK]
- Confusing preorder or postorder with inorder
- Expecting different order after conversion
- Misunderstanding BST traversal properties
Ready to prove it?
Pass the test and this pattern moves unknown
