Back to Practice Dashboard
Top 150 InterviewMedium

Distinct Subsequences

Learn how to solve the 'Distinct Subsequences' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Medium

Given two strings s and t, return the number of distinct subsequences of s which equals t.

A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Write a function numDistinct(s: str, t: str) -> int.

Constraints
  • 1 <= len(s), len(t) <= 1000
  • s and t consist of English letters

Examples

Example 1
Input
s = "rabbbit", t = "rabbit"
Output
3
Explanation

There are 3 ways you can generate "rabbit" from s: **rab**b**bit**, **ra**b**bbit**, **rab**bb**it**.

Example 2
Input
s = "babgbag", t = "bag"
Output
5
Explanation

There are 5 ways you can generate "bag" from s.

Need a Hint?
Define subproblem states, establish the recurrence relation, and use memoization (top-down) or tabulation (bottom-up).
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor