Problem Description
Given a string text and an array of strings words, return an array of all index pairs [i, j] such that the substring text[i...j] is one of the words in words. The answer should be returned in sorted order where pairs are sorted by the first index and in case of a tie, by the second index.
Key Insights
- The input size is small enough (text length up to 100, words up to 20) to allow a brute-force approach.
- For each word in words, iterate over every possible starting index in text and check if a substring of the matching length equals the word.
- Alternatively, building a trie from the words could be used for more efficient multi-string matching in larger inputs.
- Overlapping matches are allowed, so ensure every possible starting position is checked.
- Sorting the result at the end guarantees the required order.
Space and Time Complexity
Time Complexity: O(n * m * k) where n is the length of text, m is the number of words, and k is the average length of a word. Space Complexity: O(1) (ignoring the space for the output), as only a result list is maintained.
Solution
We solve the problem by iterating through each word in words and, for each word, scanning through the text to see if the substring starting at that index matches the word. If it does, record the starting and ending indices as a pair. After processing all words, sort the list of index pairs to meet the output requirements. This straightforward approach leverages simple substring comparisons.