Problem 459405 · medium · Level 04 Non-Linear Data Structures

Highlighting Glossary Terms in a Line

trie · string matching

A reading app highlights glossary terms inside a line of text written without spaces. Given the line text and a list of distinct glossary words, return every pair [i, j] for which text[i..j] (both ends included) is a glossary word; highlights may overlap. Sort the pairs by i, then by j.

Examples

Input:  text = "windowsillflowerpot", words = ["window", "sill", "windowsill", "flower", "pot"]
Output: [[0, 5], [0, 9], [6, 9], [10, 15], [16, 18]]

Input:  text = "banana", words = ["ana", "an", "nan"]
Output: [[1, 2], [1, 3], [2, 4], [3, 4], [3, 5]]
Explanation: occurrences may overlap: "ana" appears at 1..3 and again at 3..5.

Constraints

  • 0 <= len(text) <= 5000, 0 <= len(words) <= 1000, words have length 1..50
  • Lowercase letters only
  • Target: O(len(text) * L) where L is the length of the longest word

Goals

  • Scan a text from every start position along a trie
  • Bound the inner loop by the longest stored word instead of the text length
Starting Python…