Distinct subsequences

Dynamic Programming DP on strings Hard

Given two strings s and t, return the number of distinct subsequences of s that equal t.


A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde" while "aec" is not.


The task is to count how many different ways we can form t from s by deleting some (or no) characters from s. Return the result modulo 109+7.

Examples:

Input: s = "axbxax", t = "axa"


Output: 2


Explanation: In the string "axbxax", there are two distinct subsequences "axa":


(a)(x)bx(a)x

(a)xb(x)(a)x

Input: s = "babgbag", t = "bag"


Output: 5


Explanation: In the string "babgbag", there are five distinct subsequences "bag":


(ba)(b)(ga)(g)

(ba)(bg)(ag)

(bab)(ga)(g)

(bab)(g)(ag)

(babg)(a)(g)

Input: s = "abcde", t = "ace"

Constraints

  • 1 <= s.length, t.length <= 1000

Hints

  • Define dp[i][j] as the number of ways to form t[0:j] using s[0:i].
  • "If s[i-1] == t[j-1], we can either: Use s[i-1] to match t[j-1] (dp[i-1][j-1]). Ignore s[i-1] and continue matching (dp[i-1][j]) and If s[i-1] ≠ t[j-1], we must ignore s[i-1]."

Company Tags

Target Riot Games Swiggy Byju's AMD Bungie Databricks Johnson & Johnson PayPal Siemens Healthineers McKinsey & Company Stripe Bloomberg ARM Nutanix Etsy Optum Twilio Texas Instruments GE Healthcare Seagate Technology Pinterest Visa Western Digital Zomato Google Microsoft Amazon Meta Apple Netflix Adobe