Convert Sorted Array to Balanced BST in DSA Python - Time & Space Complexity
We want to understand how the time needed to build a balanced binary search tree changes as the input array grows.
Specifically, how does the number of steps grow when converting a sorted array into a balanced BST?
Analyze the time complexity of the following code snippet.
def sorted_array_to_bst(nums):
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sorted_array_to_bst(nums[:mid])
root.right = sorted_array_to_bst(nums[mid+1:])
return root
This code builds a balanced BST 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 processed once to create a node, but slicing creates new arrays at each step.
Each recursive call splits the array roughly in half, creating nodes for each element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 node creations plus slicing overhead |
| 100 | About 100 node creations plus more slicing |
| 1000 | About 1000 node creations plus even more slicing |
Pattern observation: The number of node creations grows linearly with input size, but slicing arrays adds extra cost making it slower than just O(n).
Time Complexity: O(n log n)
This means the time grows a bit faster than the input size because slicing arrays takes extra time at each step.
[X] Wrong: "The time complexity is O(n) because each element is processed once."
[OK] Correct: Although each element creates one node, slicing the array at each recursive call takes extra time, adding up to O(n log n).
Understanding this complexity helps you explain how recursion and data copying affect performance, a key skill in coding interviews.
"What if we avoided slicing by passing start and end indexes instead? 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: Reason about balanced BST
A balanced BST has roughly equal nodes on left and right subtrees, which reduces height and improves search time.Final Answer:
To create a BST with minimal height -> Option AQuick Check:
Balanced BST = minimal height [OK]
- Thinking the array is reversed
- Confusing BST with linked list
- Ignoring balance and height
nums to a balanced BST using recursion?Solution
Step 1: Check parameter type
The input is a sorted array, sonumsshould be a list of integers:list[int].Step 2: Check return type
The function returns the root of a BST, which is a TreeNode or None, soOptional[TreeNode]is correct.Final Answer:
def sortedArrayToBST(nums: list[int]) -> Optional[TreeNode]: -> def sortedArrayToBST(nums: list[int]) -> Optional[TreeNode]:Quick Check:
Input list[int], output Optional[TreeNode] [OK]
- Using int instead of list[int] for input
- Returning int or list instead of TreeNode
- Missing Optional for possible None return
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sortedArrayToBST(nums):
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sortedArrayToBST(nums[:mid])
root.right = sortedArrayToBST(nums[mid+1:])
return root
root = sortedArrayToBST([-10, -3, 0, 5, 9])
# Inorder traversal function
def inorder(node):
return inorder(node.left) + [node.val] + inorder(node.right) if node else []
print(inorder(root))Solution
Step 1: Understand inorder traversal
Inorder traversal of a BST returns the sorted array in ascending order.Step 2: Trace the code output
The code builds a balanced BST from the sorted array, so inorder traversal returns the original sorted array: [-10, -3, 0, 5, 9].Final Answer:
[-10, -3, 0, 5, 9] -> Option BQuick Check:
Inorder traversal = sorted array [OK]
- Confusing preorder or postorder with inorder
- Expecting reversed or shuffled output
- Not understanding recursion splits
def sortedArrayToBST(nums):
if len(nums) == 0:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sortedArrayToBST(nums[mid+1:])
root.right = sortedArrayToBST(nums[:mid])
return rootSolution
Step 1: Check subtree assignments
The left subtree should be built from elements before mid:nums[:mid], and right subtree from elements after mid:nums[mid+1:].Step 2: Identify swapped slices
The code assigns left subtree fromnums[mid+1:]and right subtree fromnums[:mid], which is reversed.Final Answer:
Left and right subtree slices are swapped -> Option DQuick Check:
Left subtree = nums[:mid], right subtree = nums[mid+1:] [OK]
- Swapping left and right subtree slices
- Incorrect base case check
- Wrong mid index calculation
[1, 2, 2, 3, 4, 4, 5], which approach correctly builds a balanced BST that includes all duplicates?Solution
Step 1: Understand duplicates in sorted array
Duplicates appear consecutively; to keep all, do not remove them before building BST.Step 2: Balanced BST construction with duplicates
Picking the middle element as root and recursively building left and right subtrees preserves duplicates and balance.Final Answer:
Use middle element as root, recursively build left and right subtrees including duplicates -> Option CQuick Check:
Middle element root keeps duplicates balanced [OK]
- Removing duplicates before building BST
- Picking always leftmost element as root
- Inserting elements one by one causing imbalance
Ready to prove it?
Pass the test and this pattern moves unknown
