Count Structurally Distinct BSTs That Can Store N Account IDs

Last updated: November 29, 2026

Quick Overview

Given n, return how many structurally unique binary search trees can store the IDs 1 through n.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given n, return how many structurally unique binary search trees can store the IDs 1 through n.

A Meta technical screen question at the boundary of trees and DP. The interviewer checks that you see choosing the root splits the problem into independent left and right subproblems, and may ask you to recognize the Catalan numbers.

What the Interviewer Expects
  • Choose each value as the root
  • Note left and right subtree counts multiply
  • Define G(n) depending only on size, not values
  • Build the table bottom-up
  • Mention the Catalan closed form
Key Topics to Cover
Dynamic programming
Catalan numbers
Binary search trees
Combinatorics
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you generate all the trees, not just count them?
  • What is the closed form and its growth rate?
  • How would you compute this modulo a prime for large n?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input is an integer n from 0 to about 19 (counts fit in 64 bits). Return the number of BST shapes holding keys 1..n. By convention n = 0 gives 1 (the empty tree)....

High-Level Design

If key r is the root, keys 1..r-1 form the left subtree and r+1..n the right subtree. The number of shapes depends only on how many keys a subtree holds, not on which keys, because BST order fix...


Submit Your Answer
Markdown supported