Solving Leetcode Interviews in Seconds with AI: Distinct Subsequences
Introduction
In this blog post, we will explore how to solve the LeetCode problem "115" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given two strings s and t, return the number of distinct subsequences of s which equals t. The test cases are generated so that the answer fits on a 32-bit signed integer. Example 1: Input: s = "rabbbit", t = "rabbit" Output: 3 Explanation: As shown below, there are 3 ways you can generate "rabbit" from s. rabbbit rabbbit rabbbit Example 2: Input: s = "babgbag", t = "bag" Output: 5 Explanation: As shown below, there are 5 ways you can generate "bag" from s. babgbag babgbag babgbag babgbag babgbag Constraints: 1 <= s.length, t.length <= 1000 s and t consist of English letters.
Explanation
Here's the breakdown of the approach, followed by the Python code:
- Dynamic Programming: We'll use dynamic programming to solve this problem.
dp[i][j]will store the number of distinct subsequences ofs[:i]that equalt[:j]. - Base Cases: If
tis empty, there's one way to form it from anys(empty subsequence). Ifsis empty, andtis not, there are zero ways. Recursive Relation: If
s[i-1] == t[j-1], we can either use that character insto form the subsequence, or ignore it. If they are not equal, we can only ignore the character ins.Runtime Complexity: O(m*n), where m is the length of
sand n is the length oft. Storage Complexity: O(m*n).
Code
def num_distinct(s: str, t: str) -> int:
"""
Given two strings s and t, return the number of distinct subsequences of s which equals t.
Example:
----------
>>> num_distinct("rabbbit", "rabbit")
3
>>> num_distinct("babgbag", "bag")
5
"""
n = len(s)
m = len(t)
# dp[i][j] stores the number of distinct subsequences of s[:i] which equals t[:j]
dp = [[0] * (m + 1) for _ in range(n + 1)]
# Base case: If t is empty, there's one way to form it from any s (empty subsequence)
for i in range(n + 1):
dp[i][0] = 1
# Fill the dp table
for i in range(1, n + 1):
for j in range(1, m + 1):
if s[i - 1] == t[j - 1]:
# If the characters match, we can either use the character from s
# or ignore it
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
else:
# If the characters don't match, we can only ignore the character from s
dp[i][j] = dp[i - 1][j]
return dp[n][m]