1. Brute Force

class Solution:
    def indexPairs(self, text: str, words: List[str]) -> List[List[int]]:
        n = len(text)
        res = []
        for word in words:
            for i in range(n - len(word) + 1):
                if text[i:i + len(word)] == word:
                    res.append([i, i + len(word) - 1])
        res.sort()
        return res

Time & Space Complexity

  • Time complexity: O(m∗n∗k+plog⁡p)O(m * n * k + p \log p)
  • Space complexity: O(p)O(p)

Where nn is the length of the string texttext, mm is the number of words, kk is the average length of a word, and pp is the number of index pairs in the output.


2. Hash Set

class Solution:
    def indexPairs(self, text: str, words: List[str]) -> List[List[int]]:
        wordSet = set(words)
        n = len(text)
        res = []
        for i in range(n):
            for j in range(i, n):
                if text[i:j + 1] in wordSet:
                    res.append([i, j])
        return res

Time & Space Complexity

  • Time complexity: O(m∗k+n3)O(m * k + n ^ 3)
  • Space complexity: O(m∗k)O(m * k)

Where nn is the length of the string texttext, mm is the number of words, and kk is the average length of a word.


3. Trie

class TrieNode:
    def __init__(self):
        self.children = {}
        self.isWord = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def addWord(self, word):
        curr = self.root
        for c in word:
            if c not in curr.children:
                curr.children[c] = TrieNode()
            curr = curr.children[c]
        curr.isWord = True

class Solution:
    def indexPairs(self, text: str, words: List[str]) -> List[List[int]]:
        trie = Trie()
        for w in words:
            trie.addWord(w)

        n = len(text)
        res = []
        for i in range(n):
            curr = trie.root
            for j in range(i, n):
                if text[j] not in curr.children:
                    break
                curr = curr.children[text[j]]
                if curr.isWord:
                    res.append([i, j])

        return res

Time & Space Complexity

  • Time complexity: O(m∗k+n2)O(m * k + n ^ 2)
  • Space complexity: O(m∗k)O(m * k)

Where nn is the length of the string texttext, mm is the number of words, and kk is the average length of a word.