Find number of occurrences of string1 in string-2. (string 1 characters shouldn't necessarily be together in string 2 but in order)
Question:
Given two strings:
s1 = "abc"
s2 = "abcbcabb"
Answer is 3
Because "abc" can be formed in s2 by taking characters at index (0,1,2),(0,1,4),(0,3,4).
Please try to optimize time and space complexity.
Answers:
You can collect the indices per letter and use itertools.product
to generate all combinations of indices, which you can filter using a check on the sorted order:
from collections import defaultdict
from itertools import product
s1 = "abc"
s2 = "abcbcabb"
d = defaultdict(list)
for i,c in enumerate(s2):
d[c].append(i)
# {'a': [0, 5], 'b': [1, 3, 6, 7], 'c': [2, 4]}
out = sum(1 for l in product(*(d[c] for c in s1))
if all(a<b for a,b in zip(l, l[1:])))
output: 3
output for s1 = 'abcb'
: 7
Given two strings:
s1 = "abc"
s2 = "abcbcabb"
Answer is 3
Because "abc" can be formed in s2 by taking characters at index (0,1,2),(0,1,4),(0,3,4).
Please try to optimize time and space complexity.
You can collect the indices per letter and use itertools.product
to generate all combinations of indices, which you can filter using a check on the sorted order:
from collections import defaultdict
from itertools import product
s1 = "abc"
s2 = "abcbcabb"
d = defaultdict(list)
for i,c in enumerate(s2):
d[c].append(i)
# {'a': [0, 5], 'b': [1, 3, 6, 7], 'c': [2, 4]}
out = sum(1 for l in product(*(d[c] for c in s1))
if all(a<b for a,b in zip(l, l[1:])))
output: 3
output for s1 = 'abcb'
: 7