Convert Sorted Array to Balanced BST in DSA Java - Time & Space Complexity
We want to know 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 we convert a sorted array into a balanced BST?
Analyze the time complexity of the following code snippet.
public TreeNode sortedArrayToBST(int[] nums) {
return buildBST(nums, 0, nums.length - 1);
}
private TreeNode buildBST(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 = buildBST(nums, left, mid - 1);
node.right = buildBST(nums, mid + 1, right);
return node;
}
This code builds a balanced BST by choosing the middle element as root and recursively building left and right subtrees.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls that split the array and create tree nodes.
- How many times: Each element in the array is visited exactly once to create a node.
Each element leads to one node creation and recursive calls split the array evenly.
| 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 needed 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, and the recursive calls split the array without overlapping work, so the total work is linear, not exponential.
Understanding this time complexity helps you explain how recursion and divide-and-conquer work together efficiently in building balanced trees.
"What if we changed the code to always pick the first element as root instead of the middle? 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 benefits
A balanced BST ensures search operations are efficient, typically O(log n) time, by minimizing height.Final Answer:
To create a BST with minimal height for efficient search -> Option DQuick Check:
Balanced BST = minimal height = efficient search [OK]
- Thinking the array needs to be reversed
- Confusing BST with linked list
- Ignoring the balance requirement
Solution
Step 1: Identify parameters needed for recursion
The recursive function needs the array and two indices (left and right) to define the current subarray.Step 2: Check return type and parameters
The function returns a TreeNode (root of subtree) and takes int[] nums, int left, int right as parameters.Final Answer:
public TreeNode sortedArrayToBST(int[] nums, int left, int right) -> Option AQuick Check:
Recursive BST function needs array + left + right indices [OK]
- Missing left and right indices parameters
- Wrong return type (void or int)
- Using mid as parameter instead of indices
int[] nums = {1, 2, 3, 4, 5};
TreeNode root = sortedArrayToBST(nums, 0, nums.length - 1);
printInorder(root);
Assuming printInorder prints nodes in inorder.Solution
Step 1: Understand inorder traversal of BST
Inorder traversal of a BST always returns the sorted order of elements.Step 2: Check input array and output
The input array is sorted: [1, 2, 3, 4, 5]. The inorder traversal of the BST built from it will be the same sorted array.Final Answer:
[1, 2, 3, 4, 5] -> Option AQuick Check:
Inorder traversal of BST = sorted array [OK]
- Confusing preorder or postorder with inorder
- Expecting reversed or shuffled output
- Not understanding BST property
public TreeNode sortedArrayToBST(int[] nums, int left, int right) {
if (left > right) return null;
int mid = (left + right) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums, left, mid - 1);
root.right = sortedArrayToBST(nums, mid + 1, right);
return root;
}
// Called with sortedArrayToBST(nums, 0, nums.length);Solution
Step 1: Check the initial call parameters
The function expects right to be the last valid index, but the call uses nums.length which is out of bounds.Step 2: Understand array indexing
Array indices go from 0 to nums.length - 1, so right should be nums.length - 1.Final Answer:
The initial call uses wrong right index -> Option BQuick Check:
Right index must be nums.length - 1, not nums.length [OK]
- Passing nums.length as right index
- Ignoring zero-based indexing
- Assuming mid calculation causes overflow here
int[] nums = {1, 2, 2, 3, 4, 4, 5}; Which statement about the balanced BST created by sortedArrayToBST(nums, 0, nums.length - 1) is true?Solution
Step 1: Understand BST property with duplicates
BST can contain duplicates; they are usually placed consistently either left or right subtree.Step 2: Check behavior of conversion from sorted array
The conversion uses array elements as nodes directly, so duplicates appear as separate nodes in the tree.Final Answer:
The BST will contain duplicate nodes for repeated values -> Option CQuick Check:
Duplicates in array = duplicates in BST nodes [OK]
- Assuming duplicates are removed automatically
- Thinking duplicates cause errors
- Believing duplicates go only to left subtree
Ready to prove it?
Pass the test and this pattern moves unknown
