oneby7

2-D Dynamic Programming Two strings

562. Distinct Subsequences

Hard

You are given two strings, s and t. Count the ways to pick letters of s, keeping their order, so that the picked letters spell t.

In other words, count the subsequences of s that are equal to t. A subsequence is what is left after deleting some letters, or none, without changing the order of the rest. Two ways are different if they pick a different set of positions in s, even when they spell the same string.

The count can be very large, so return it modulo 109 + 7. If t cannot be spelled at all, the answer is 0.

Example 1

Input: s = "banana", t = "ana"

Output: 4

Explanation: Counting positions from 0, the letters at (1, 2, 3), (1, 2, 5), (1, 4, 5) and (3, 4, 5) spell "ana".

Example 2

Input: s = "listen", t = "silent"

Output: 0

Explanation: s has every letter of t, but in a different order. Both strings have six letters, so the only way would be to pick all of s.

Example 3

Input: s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" t = "aaaaaaaaaaaaaaaaaaaa"

Output: 846527861

Explanation: s has 40 letters and t has 20. Any 20 of the 40 letters spell t, which gives 137846528820 ways. Modulo 109 + 7 that is 846527861.

Check your understanding

Work out the answer for this input before you write any code.

s = "abab", t = "ab"

Constraints

  • 1 ≤ s.length ≤ 104
  • 1 ≤ t.length ≤ 1000
  • s and t hold only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.