Bounded Range Segment Calculator 7 — Problem Statement & Solution Guide
Problem Description
You are provided with a string s of length N and a target subsequence string t of length M. Your task is to determine the number of distinct ways to select characters from s such that they form the exact sequence t in order, without necessarily being contiguous. This is a classic subsequence verification and counting problem. Return the total count of such valid subsequences. If no such subsequence exists, return 0. Since the result can be very large, return the answer modulo 10^9 + 7.
The selection must preserve the relative order of characters in t. For example, if t = "abc", you must pick an 'a' from s at index i, then a 'b' at index j > i, and then a 'c' at index k > j. The indices i, j, k must be strictly increasing. Each unique combination of indices (i, j, k) counts as a distinct way.
Input: Two strings, s (the source string) and t (the target subsequence).
Output: An integer representing the number of distinct subsequences of s that equal t, modulo 10^9 + 7.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Bounded Range Segment Calculator 7"
WHY DOES IT MATTER?
This pattern is essential for problems involving sequence matching, pattern recognition, and combinatorial counting. It teaches the fundamental DP technique of breaking down a problem into overlapping subproblems and using memoization or tabulation to avoid redundant calculations, which is a cornerstone of algorithmic efficiency.
OPTIMIZATION CHALLENGE
The key insight is to reduce the 2D DP table to a 1D array by iterating through the source string s and updating the DP states for the target string t in reverse order. This prevents the current iteration's updates from affecting subsequent calculations in the same pass, effectively simulating the 2D table with $O(M)$ space.
REAL-WORLD CONNECTION
This is analogous to log parsing in distributed systems, where you need to count the number of times a specific sequence of events (e.g., 'login', 'purchase', 'logout') occurs in a massive, non-contiguous stream of user activity logs. It is also relevant in bioinformatics for counting occurrences of a gene sequence within a larger DNA strand.
In interviews, always start by defining the DP state clearly: dp[i] represents the number of ways to form the prefix t[0..i-1] using the characters processed so far in s. Emphasize the reverse iteration to show you understand the dependency graph and how to optimize space without sacrificing correctness.
COMPLEXITY AT A GLANCE
O(N * M)O(M)Core Theory — Why This Approach?
The problem of counting distinct subsequences is a classic application of Dynamic Programming (DP) that relies on the principle of optimal substructure. The core state is defined by two indices: i representing the current position in the target string t, and j representing the current position in the source string s. The recurrence relation is derived from two choices at each step: either we skip the current character in s (transitioning to dp[i][j+1]), or, if s[j] matches t[i], we can either use it (transitioning to dp[i+1][j+1]) or skip it (transitioning to dp[i][j+1]). This creates a binary decision tree that, if explored naively, results in exponential time complexity $O(2^N)$, which is infeasible for large inputs.
Interview Questions on This Problem
Q1At a fintech platform processing high-volume transaction logs, how would you adapt this subsequence counting algorithm to handle a stream of data where the source string `s` is too large to fit in memory?
You would use a space-optimized DP approach that only tracks the current row of the DP table, reducing space complexity to $O(M)$. For streaming, you process characters of s one by one, updating the DP array in reverse order (from $M-1$ down to $0$) to avoid overwriting values needed for the current iteration. This allows the system to count valid subsequences in a single pass with constant memory overhead relative to the source length.
Q2In a high-growth startup building a search engine, how would you modify this algorithm to count only *distinct* subsequences, ensuring that duplicate characters in `s` do not lead to overcounting identical sequences in `t`?
To count distinct subsequences, you must track the last occurrence of each character in t. When processing s[j], if s[j] matches t[i], you subtract the count of subsequences formed by the previous occurrence of t[i] to avoid double-counting. This requires maintaining an auxiliary array lastSeen of size equal to the alphabet size, adjusting the DP transition to dp[i+1][j+1] = dp[i][j+1] + dp[i][j] - dp[i][lastSeen[t[i]]].
Q3For a global product company's recommendation system, how would you optimize the time complexity if the target string `t` is very short (e.g., length 3) but the source string `s` is extremely long (e.g., $10^9$)?
If M is small, you can use a combinatorial approach or a specialized DP that runs in $O(N \cdot M)$. However, for very large N, you can precompute prefix sums of character frequencies. For a fixed t, the count can be calculated by iterating through s and updating a small state vector of size $M$. The key optimization is recognizing that the DP table width is bounded by M, allowing for $O(N)$ time complexity with $O(M)$ space, which is optimal for streaming large datasets.
Examples
Input
s = "rabbbit", t = "rabbit"
Output
3
Explanation: We need to find the number of ways to form "rabbit" from "rabbbit". The valid index combinations are: (0,1,2,4,5), (0,1,3,4,5), and (0,2,3,4,5). Thus, there are 3 distinct ways.
Input
s = "abc", t = "ac"
Output
1
Explanation: The only way to form "ac" is by picking 'a' at index 0 and 'c' at index 2. The 'b' at index 1 is skipped. Thus, there is exactly 1 valid subsequence.
Input
s = "aaaa", t = "aa"
Output
6
Explanation: We need to pick two 'a's from four 'a's. The number of ways to choose 2 indices out of 4 is C(4,2) = 6. The valid index pairs are (0,1), (0,2), (0,3), (1,2), (1,3), and (2,3).
Input
s = "xyz", t = "zyx"
Output
0
Explanation: The target subsequence "zyx" requires 'z' to appear before 'y' and 'y' before 'x'. However, in the source string "xyz", 'x' comes first, followed by 'y', then 'z'. Since the order is reversed, no valid subsequence exists. The result is 0.
Constraints
- 1 <= s.length <= 1000
- 1 <= t.length <= 1000
- s and t consist of lowercase English letters only
- The answer is guaranteed to fit within a 64-bit integer before modulo operation
Optimal Approach & Strategy
Use a 1D DP array of size M+1 where dp[i] represents the count of subsequences forming t[0..i-1]. Iterate through s and update dp in reverse order, adding dp[i-1] to dp[i] when s[j] matches t[i-1], achieving $O(N \cdot M)$ time and $O(M)$ space.
Brute Force Approach
Recursively explore all possible subsets of characters in s to check if they form t, which results in exponential time complexity $O(2^N)$. This approach is infeasible for large inputs due to the massive number of overlapping subproblems.
Verified Code Solutions
function solution(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum;
}class Solution {
public:
int solution(vector<int> nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
};class Solution {
public int solution(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
}def solution(nums):
sum = 0
for num in nums:
sum += num
return sumfunction solution(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum;
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.