Convert Sorted Array to BST solution explained
To convert a sorted array to a height-balanced binary search tree, make the middle element the root, then build the left subtree from the elements before it and the right subtree from the elements after it, recursively. Because each half differs in size by at most one, every node's subtrees differ in height by at most one. It runs in O(n) time with O(log n) recursion depth when you pass index bounds instead of copying slices.
By Evin JohnPublished 7 min read
The task, restated
You get an array of numbers in strictly increasing order. Build a binary search tree that holds exactly those values: every value in a node's left subtree is smaller than the node, every value in its right subtree is larger. The tree must also be height-balanced, meaning that at every node the heights of the two subtrees differ by no more than one. Return the root.
0
/ \
-7 9
\ / \
-2 4 13With an even number of elements there are two middles, so there are several valid trees. Picking the upper middle at the top would make 4 the root instead of 0, and that tree is just as correct. Ask the interviewer whether any balanced tree is accepted; it usually is, and a careful grader checks the properties rather than one exact shape. For [1, 3, 5, 7, 9], the root is 5 with 1 and 7 as its children.
What the interviewer is checking
The code is short, so the conversation carries the weight. The interviewer wants to hear why the middle element is the right root (it splits the remaining values evenly, which is what keeps the heights close), what the base case is, and whether your recursion copies the array. Slicing in Python or JavaScript creates new arrays at every level, which quietly turns an O(n) answer into O(n log n) time and extra memory. Passing two indexes avoids that.
- Sorted linked list instead of an array. You cannot jump to the middle. Either find it with slow and fast pointers each time (O(n log n)), or count the nodes and build the tree in in-order sequence while advancing a single list pointer (O(n)).
- Rebalance an existing BST. Read it in order into an array, then run this exact algorithm.
- Return the tree as a level-order array. Build the tree first, then do a breadth-first walk with nulls for missing children.
- Iterative version. Use a stack of (node, low, high) tasks instead of recursion.
A naive attempt: insert in sorted order
Plain BST insertion with the values in their given order puts each new, larger value to the right of the previous one. The result is a valid search tree shaped like a linked list, with height n, so it fails the balance requirement. It is worth mentioning only to show why the order of insertion matters. Inserting into a self-balancing tree such as an AVL tree would pass, at O(n log n) time and a lot of rotation code, which is far more than the problem needs.
The standard approach: middle as root, recurse on halves
Work on an index range from low to high, inclusive. If low is greater than high, the range is empty and the subtree is null. Otherwise take mid as (low + high) // 2, create a node with that value, build its left child from low to mid minus 1 and its right child from mid plus 1 to high. The two halves have sizes that differ by at most one, so by induction their heights differ by at most one, and the in-order sequence of the result is the original array, which makes it a valid BST.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sorted_array_to_bst(nums):
def build(low, high):
if low > high:
return None
mid = (low + high) // 2
node = TreeNode(nums[mid])
node.left = build(low, mid - 1)
node.right = build(mid + 1, high)
return node
return build(0, len(nums) - 1)class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function sortedArrayToBST(nums) {
function build(low, high) {
if (low > high) return null;
const mid = Math.floor((low + high) / 2);
const node = new TreeNode(nums[mid]);
node.left = build(low, mid - 1);
node.right = build(mid + 1, high);
return node;
}
return build(0, nums.length - 1);
}If the interviewer asks for no recursion, the stack version below does the same work. Each task says "fill this node from this range". It is also a nice way to show that you understand what the recursion was doing, rather than relying on it.
def sorted_array_to_bst_iter(nums):
if not nums:
return None
mid = (len(nums) - 1) // 2
root = TreeNode(nums[mid])
stack = [(root, 0, mid - 1, "left"), (root, mid + 1, len(nums) - 1, "right")]
while stack:
parent, low, high, side = stack.pop()
if low > high:
continue
mid = (low + high) // 2
child = TreeNode(nums[mid])
setattr(parent, side, child)
stack.append((child, low, mid - 1, "left"))
stack.append((child, mid + 1, high, "right"))
return rootComplexity
| Approach | Time | Extra space | Balanced? |
|---|---|---|---|
| Insert in sorted order into a plain BST | O(n²) | O(n) recursion if done recursively | No, height n |
| Insert into a self-balancing tree | O(n log n) | O(log n) | Yes |
| Middle as root, recursing on slices | O(n log n) from copying | O(n) in copies | Yes |
| Middle as root, recursing on indexes | O(n) | O(log n) recursion | Yes |
The output tree itself takes O(n) space in every version; the table counts only the working memory on top of it.
Edge cases
- An empty array returns null (the range 0 to -1 is empty).
- One element returns a single node.
- Two elements: lower middle gives the first as root with the second on its right; either choice is balanced.
- Negative numbers and zero need no special handling.
- Duplicates are usually ruled out by "strictly increasing". If allowed, agree on which side equal values go before coding.
Mistakes to avoid
- Using slices and then claiming O(n) time.
- An off-by-one in the ranges, such as recursing on low to mid, which repeats the middle value or loops forever when low equals high.
- Testing against one exact tree from memory, then thinking a different valid tree is wrong.
- Confusing "balanced" with "complete". The tree does not need its last level filled from the left.
- Writing (low + high) / 2 in JavaScript without Math.floor, which produces a fractional index.
How to explain it out loud
Fictional example
- Candidate
- In-order traversal of a BST is sorted, so whatever tree I build, reading it in order must give back this array. The only choice is the root.
- Candidate
- If I pick the middle, the two sides get sizes that differ by at most one. Applying the same rule to each side keeps every subtree balanced.
- Candidate
- I will pass low and high instead of slicing, so each element is touched once. O(n) time and log n depth.
- Interviewer
- Would the upper middle also work?
- Candidate
- Yes, it gives a different but equally balanced tree, so I would check the answer with properties, not by comparing shapes.
Related walkthroughs
Delete Node in a BST works on the tree this problem builds, and one simple way to rebalance after many deletions is to rebuild with this exact method. Populating Next Right Pointers links the levels of a balanced tree. Sum Root to Leaf Numbers is another short recursive tree exercise, and Merge Intervals is a good contrast on working with sorted input.
Where Natively fits
Short problems like this are good for practicing the explanation, not just the code. On your Mac or Windows PC, Natively can read the problem from a screenshot, and if you freeze on why the middle element keeps the tree balanced, you can ask it for that one idea and continue on your own. Its transcript of the mock lets you check later that you mentioned index bounds versus slicing. More on the AI interview assistant.
Questions people ask
How do you convert a sorted array to a balanced BST?
Make the middle element the root, build the left subtree from the elements before it and the right subtree from those after it, and repeat on each half.
Why does choosing the middle keep the tree balanced?
The two halves differ in size by at most one, so applying the same rule recursively keeps every node's subtree heights within one of each other.
What is the time complexity of Convert Sorted Array to BST?
O(n) when you pass index bounds, with O(log n) recursion depth. Slicing the array at each step adds copying and makes it O(n log n).
Is there only one correct answer?
No. With an even number of elements either middle works, so several balanced trees are valid. Check the result by its properties, not one fixed shape.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
