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.

Asked By: Nirupam Suraj

||

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

Answered By: mozway
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.