Number of Strings That Appear as Substrings in Word

Solution
class Solution:
    def numOfStrings(self, patterns: List[str], word: str) -> int:
        def check(pattern: str, word: str) -> bool:
            m = len(pattern)
            n = len(word)
            # generate the prefix array of the pattern
            pi = [0] * m
            j = 0
            for i in range(1, m):
                while j and pattern[i] != pattern[j]:
                    j = pi[j - 1]
                if pattern[i] == pattern[j]:
                    j += 1
                pi[i] = j
            # using prefix arrays for matching
            j = 0
            for i in range(n):
                while j and word[i] != pattern[j]:
                    j = pi[j - 1]
                if word[i] == pattern[j]:
                    j += 1
                if j == m:
                    return True
            return False
            
        res = 0
        for pattern in patterns:
            res += check(pattern, word)
        return res

Time Complexity

O(n Σ m_i)

Space Complexity

O(max(m_i)