Skip to content

Conversation

@kaif969
Copy link
Contributor

@kaif969 kaif969 commented Oct 29, 2025

PR Title Format: 96. Unique Binary Search Trees.cpp

Intuition

Choose any value i (1 ≤ i ≤ N) as root. Values [1..i-1] must go to the left subtree (size i-1) and values [i+1..N] to the right subtree (size N-i). If G(n) is the number of unique BSTs with n nodes, then for a fixed root i there are G(i-1) * G(N-i) distinct BSTs (left and right subtrees combine independently). Summing over all possible roots yields the recurrence:

G(N) = sum_{i=1..N} G(i-1) * G(N-i)

Base cases: G(0) = 1 (empty tree), G(1) = 1.

This is the Catalan-number recurrence. A DP solution computes G[0..N] bottom-up (or uses memoized recursion) in O(N^2) time and O(N) space. Example: for N = 3,
G(3) = G(0)G(2) + G(1)G(1) + G(2)G(0) = 2 + 1 + 2 = 5.

Approach

We solve this using the Catalan-number DP recurrence with two equivalent implementation styles: top-down memoized recursion or bottom-up iteration.

  1. Initialization

    • Use a dp array of size 21 (indices 0..20) because n ≤ 20. Initialize dp[0] = 1 and dp[1] = 1.
    • Use a 64-bit type (long long / uint64_t) if you allow n = 20, since Catalan(20) = 6,564,120,420 exceeds 32-bit signed range.
  2. Recurrence

    • For each n ≥ 2:
      dp[n] = sum_{i=1..n} dp[i-1] * dp[n-i]
    • Rationale: choosing value i as root produces independent choices for left (i-1 nodes) and right (n-i nodes) subtrees, so counts multiply; summing over all possible roots counts all BST shapes.
  3. Top-down (memoized recursion)

    • If dp[n] is already computed, return it (avoids repeated work).
    • Otherwise compute dp[n] by looping i=1..n and accumulating numTrees(i-1) * numTrees(n-i) where recursive calls fill smaller dp entries.
    • Store and return dp[n].
  4. Bottom-up (iterative DP)

    • For nodes from 2..n: for root=1..nodes: dp[nodes] += dp[root-1] * dp[nodes-root]
    • This avoids recursion overhead and computes each dp value exactly once.
  5. Complexity

    • Time: O(n^2) due to the nested sum over sizes.
    • Space: O(n) for the dp array.

Code Solution (C++)

class Solution {
public:
    int dp[20]{};
    int numTrees(int n) {
        if(n <= 1) return 1;
        if(dp[n]) return dp[n];
        for(int i = 1; i <= n; i++) 
            dp[n] += numTrees(i-1) * numTrees(n-i);
        return dp[n];
    }
};

Related Issues

#259

By submitting this PR, I confirm that:

  • [✅] This is my original work not totally AI generated
  • [✅] I have tested the solution thoroughly on leetcode
  • [✅] I have maintained proper PR description format
  • [✅] This is a meaningful contribution, not spam

Summary by Sourcery

Introduce C++ DP-based solutions for the Candy and Unique Binary Search Trees problems on LeetCode.

New Features:

  • Add Candy.cpp implementing a two-pass DP solution to distribute candies based on ratings
  • Add Unique Binary Search Trees solution using memoized recursion to compute Catalan numbers

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 29, 2025

Reviewer's Guide

This PR introduces two LeetCode problem solutions: a two-pass greedy algorithm for the Candy problem (135) and a top-down memoized DP for counting unique Binary Search Trees (96).

Class diagram for Solution class in Unique Binary Search Trees (96)

classDiagram
class Solution {
  +int dp[20]
  +int numTrees(int n)
}
Loading

Class diagram for Solution class in Candy problem (135)

classDiagram
class Solution {
  +int candy(vector<int>& ratings)
}
Loading

File-Level Changes

Change Details Files
Implemented two-pass greedy algorithm for candy distribution
  • Initialized ratings-based count vector with 1s
  • Performed left-to-right scan to handle ascending ratings
  • Performed right-to-left scan to correct for descending ratings
  • Calculated total candies using accumulate
135. Candy.cpp
Added memoized DP solution for counting unique BSTs
  • Declared fixed-size dp array for n ≤ 20
  • Handled base cases for n ≤ 1 directly
  • Checked dp array to return cached results
  • Recursively computed dp[n] by summing products of left/right subtree counts
96. Unique Binary Search Trees.cpp

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • The dp array in the Unique BST solution is declared as size 20 but needs to support indices up to n=20, so increase it to at least dp[21] (or use a vector) to avoid out-of-bounds access.
  • Use a 64-bit type (long long or uint64_t) for Catalan numbers when n can be 20, since Catalan(20) exceeds 32-bit integer range and will overflow.
  • This PR currently includes solutions for both 'Candy' and 'Unique Binary Search Trees'—consider splitting them into separate PRs to keep each review focused.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The dp array in the Unique BST solution is declared as size 20 but needs to support indices up to n=20, so increase it to at least dp[21] (or use a vector) to avoid out-of-bounds access.
- Use a 64-bit type (long long or uint64_t) for Catalan numbers when n can be 20, since Catalan(20) exceeds 32-bit integer range and will overflow.
- This PR currently includes solutions for both 'Candy' and 'Unique Binary Search Trees'—consider splitting them into separate PRs to keep each review focused.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@SjxSubham SjxSubham linked an issue Oct 30, 2025 that may be closed by this pull request
4 tasks
@SjxSubham
Copy link
Owner

@kaif969 U are only allowed to add upto one single problem in a single PR...
so delete those xtra files and add only one file that justifies ur PR description

same goes with #268

Copy link
Contributor Author

@kaif969 kaif969 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SjxSubham delete the other two files. Please check.

@SjxSubham SjxSubham added the hacktoberest-accepted hacktoberfest-accepted label Oct 30, 2025
@SjxSubham SjxSubham merged commit 88773f7 into SjxSubham:main Oct 30, 2025
2 checks passed
@github-actions
Copy link

🎉 Congrats on getting your PR merged in, @kaif969! 🙌🏼

Thanks for your contribution every effort helps improve the project.

Looking forward to seeing more from you! 🥳✨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberest-accepted hacktoberfest-accepted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

96: Unique Binary Search Trees

2 participants