![]() |
VOOZH | about |
Given two strings s and w, find the number of times w appears as a subsequence of string s where every character of string s can be included in forming at most one subsequence.
Examples :
Input: s = "abcdeacbced", w = "bcd"
Output: 2
Explanation: The two subsequences of string w are highlighted in abcdeabced. The first subsequence is formed by (s[1], s[2] and s[3]) and second by (s[7], s[8] and s[10])
Input: s = "abcde", w = "fgh"
Output: 0
Explanation: No valid subsequences are possible.
The idea is to repeatedly try to form the subsequence w. Whenever a character from s is used in a subsequence, mark it so it cannot be reused again. Continue this process until no more subsequences can be formed.
Let us understand with an example:
Input: s = "abcdeacbced", w = "bcd"
Initialize res = 0.
Traverse the string and try to form the subsequence "bcd".
Updated string: a***eacbced
One subsequence is formed, so increment result: res = 1
Again traverse the string to form another "bcd" subsequence.
Updated string: a***eac**e*
Another subsequence is formed: res = 2
Traverse again, No more valid "bcd" subsequences can be formed.
Final result: 2
2
Time Complexity: O(n^2)
Auxiliary Space: O(1)