Top 150 Interview

Distinct Subsequences

Detailed guide and Python implementation for the 'Distinct Subsequences' problem.

問題提起

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.

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

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?
Consider using 2D DP-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

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

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。