Solving Leetcode Interviews in Seconds with AI: Distinct Subsequences II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "940" 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 a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not. Example 1: Input: s = "abc" Output: 7 Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc". Example 2: Input: s = "aba" Output: 6 Explanation: The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba". Example 3: Input: s = "aaa" Output: 3 Explanation: The 3 distinct subsequences are "a", "aa" and "aaa". Constraints: 1 <= s.length <= 2000 s consists of lowercase English letters.
Explanation
Here's an efficient solution to the problem of counting distinct non-empty subsequences of a string, along with explanations.
Approach: The core idea is to use dynamic programming. We iterate through the string
s. For each character, we double the number of subsequences seen so far (representing the option of including or not including the character). If the character has been seen before, we subtract the count of subsequences seen before the previous occurrence of that character. This avoids overcounting subsequences that would be identical due to duplicate characters.Complexity:
- Runtime: O(n), where n is the length of the string
s. - Storage: O(1), as we only store a fixed number of variables (count, last occurrence of each character).
- Runtime: O(n), where n is the length of the string
Code
def distinctSubsequences(s):
MOD = 10**9 + 7
last = {} # Dictionary to store the last seen index of each character
count = 1 # Initialize count to 1 (representing the empty subsequence)
for i, char in enumerate(s):
new_count = (2 * count) % MOD
if char in last:
new_count = (new_count - count + MOD) % MOD
count = new_count
last[char] = count - (count // 2 if char not in last else 0)
return (count - 1 + MOD) % MOD # Subtract 1 to exclude the empty subsequence