Unique Binary Search Trees

MediumDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer n, count how many structurally different binary search trees can be built that store exactly the values 1 through n, each used once. Two trees count as different if their shapes differ; because the values are fixed to 1..n and must satisfy the BST ordering, each shape has exactly one valid labeling. Return the count as an integer. For n up to 19 it fits in a signed 32-bit integer. An O(n^2) dynamic program is expected.

Examples

Input: n = 3
Output: 5
Rooting at 1 gives 2 shapes, at 2 gives 1, and at 3 gives 2, for 5 in total.
Input: n = 1
Output: 1
A single node forms one tree.

Constraints

  • 1 <= n <= 19
  • Each tree stores the values 1..n exactly once
  • The answer fits in a signed 32-bit integer

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems