Skip to main content
Back to problems
Leetcode
Medium
Dynamic Programming
DP on Strings
Strings
Google
Microsoft
Distinct Subsequences

Count how many distinct subsequences of one string equal another target string.

Acceptance 50%
Problem Statement

Given two strings s and t, count how many distinct subsequences of s are exactly equal to t.

A subsequence is formed by deleting zero or more characters from a string without changing the relative order of the remaining characters. Different deletion choices that produce the same resulting characters are still counted separately if they come from different indices.

Your task is to return the number of distinct ways to form t from s as a subsequence.

Input Format

  • Two strings s and t.
  • s is the source string.
  • t is the target string to match as a subsequence.

Output Format

  • Return an integer representing the number of distinct subsequences of s equal to t.

Constraints

  • The answer may be large; use a numeric type that can store the result.
  • If t is longer than s, the answer is 0.
  • An empty target string can always be formed in exactly one way.
  • A concise interview setting usually assumes lowercase or ASCII strings, but the core logic works for general strings.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "rabbbit", t = "rabbit"

Output

3

Explanation

There are 3 distinct ways to delete one of the three 'b' characters so that the remaining characters form rabbit.

Example 2

Input

s = "babgbag", t = "bag"

Output

5

Explanation

There are 5 different subsequences of s that spell bag.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.