← Meta (Facebook) bank

Meta (Facebook) · Question 44 · Trees

Kth Smallest Element in BST

TreesPythoncode⏱ O(h+k)💾 O(h)
Product-based

Problem

You are given root of BST and integer k. Find the kth smallest element.

Approach

Inorder walk counting down k; the kth visited node is the answer.

Time O(h+k)Space O(h)

How it works

  1. 1Inorder visits BST nodes in sorted order.
  2. 2Stop at the kth visit.

Sample input / output

Input:
5 3
5 3 6 2 4 x x 1
Output:
4

Constraints

1 <= k <= nodes <= 10^4.

Solution — read it, then walk it

Time O(h+k)Space O(h)Loops 1Branches 6Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesnoyesno↻ repeatyesSTARTroot, kresult = [-1]count = [k]DEFINE inorder(node)if not nodeRETURNinorder(node.left)count[0] -= 1if count[0] == 0result[0] = node.valRETURNinorder(node.right)inorder(root)RETURN result[0]CLASS TreeNodeDEFINE __init__(self,val=0, left=None,right=None)self.val = valself.left = leftself.right = rightDEFINE build_tree(values)if not valuesRETURN Noneroot = TreeNode(values[0])queue = [root]i = 1while queue and i <len(values)node = queue.pop(0)if i < len(values) andvalues[i] is not Nonenode.left =TreeNode(values[i])queue.append(node.left)i += 1if i < len(values) andvalues[i] is not Nonenode.right =TreeNode(values[i])queue.append(node.right)i += 1RETURN rootDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); k =int(next(it))vals = [None if t == 'x'else int(t) for t in[next(it) for _ i…print(kthSmallest(build_tree(vals),k))if __name__ =="__main__"main()
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

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