← Meta (Facebook) bank

Meta (Facebook) · Question 46 · Trees

Convert Sorted Array to BST

TreesPythoncode⏱ O(n)💾 O(logn)
Product-based

Problem

You are given sorted array. Convert it to height-balanced BST.

Approach

Pick the middle as root so halves stay balanced; recurse both sides.

Time O(n)Space O(logn)

How it works

  1. 1The middle element becomes the subtree root.
  2. 2Left half builds the left subtree, right half the right.

Sample input / output

Input:
5
-10 -3 0 5 9
Output:
[0, -10, 5, -3, 9]

Constraints

1 <= nums.length <= 10^4; sorted strictly increasing.

Solution — read it, then walk it

Time O(n)Space O(logn)Loops 1Branches 4Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyes↻ repeat↻ repeatyesnoSTARTnumsDEFINE helper(left, right)if left > rightRETURN Nonemid = left + (right - left)// 2root = TreeNode(nums[mid])root.left = helper(left,mid - 1)root.right = helper(mid +1, right)RETURN rootRETURN helper(0, len(nums)- 1)CLASS TreeNodeDEFINE __init__(self,val=0, left=None,right=None)self.val = valself.left = leftself.right = rightDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))nums = [int(next(it)) for _in range(n)]root =sortedArrayToBST(nums)DEFINE level_print(root)if not rootRETURN []out, queue = [], [root]while queuenode = queue.pop(0)if nodeout.append(node.val)queue += [node.left,node.right]RETURN outprint(level_print(root))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/36

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits