Skip to main content

Distinct Subsequences

Count distinct subsequences of s that equal t Example: s = "rabbbit", t = "rabbit" => 3 (rabb)b(it), (ra)b(bbit), (rab)b(bit) Example: s = "babgbag", t = "bag" => 5

Given non-empty strings s and t of lowercase English letters, return the number of distinct ways to select positions from s whose characters form t. Selected positions must keep their original order but need not be adjacent, and different selections count separately even when they form the same string. Return 0 if t cannot be formed. The answer is guaranteed to fit in a signed 32-bit integer. For example, s = "rabbbit" and t = "rabbit" produce 3.

Examples

You write

num_distinct(s: str, t: str)

  1. Example 1

    Input
    s = "rabbbit", t = "rabbit"
    returns
    3
  2. Example 2

    Input
    s = "babgbag", t = "bag"
    returns
    5

The pattern behind it

Dynamic Programming

I reach for it when

  • Brute force repeats the same subproblem.
  • You are asked for a count, a minimum or a maximum.

Say this before you type. Say the state in one sentence, then say which smaller states it reads from.

All 37 Dynamic Programming problems

Strings

I reach for it when

  • The input is text and the answer is a count, a substring or a new string.
  • You need to compare, reverse or rebuild characters.

Say this before you type. Say which array pattern the string is hiding before you touch a character.

All 51 Strings problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Count Distinct Subsequenceshard