Index Pairs of a String Problem
Description
LeetCode Problem 1065.
Given a string text and an array of strings words, return an array of all index pairs [i, j] so that the substring text[i...j] is in words.
Return the pairs [i, j] in sorted order (i.e., sort them by their first coordinate, and in case of ties sort them by their second coordinate).
Example 1:
Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
Output: [[3,7],[9,13],[10,17]]
Example 2:
Input: text = "ababa", words = ["aba","ab"]
Output: [[0,1],[0,2],[2,3],[2,4]]
Explanation: Notice that matches can overlap, see "aba" is found in [0,2] and [2,4].
Constraints:
1 <= text.length <= 1001 <= words.length <= 201 <= words[i].length <= 50textandwords[i]consist of lowercase English letters.- All the strings of
wordsare unique.
Solution
Approach: Check Every Substring Against a Set
The input is small: text has at most 100 characters, so it has only about 5000 substrings. Put the words in a hash set and test each substring text[i..j].
Trying the start i in increasing order, and for each i the end j in increasing order, produces the pairs already sorted the way the problem asks: by first coordinate, then by second. Overlapping matches, such as "aba" at [0, 2] and at [2, 4] in "ababa", come out naturally because every start is tried.
For much larger inputs a trie of the words would avoid building each substring: walk the trie from each start i and report a pair whenever a word ends.
Complexity: O(n3) time in the worst case for n = text.length (building and hashing each substring), which is fine for n <= 100; O(total length of the words) extra space for the set, besides the answer.
class Solution:
def indexPairs(self, text: str, words: List[str]) -> List[List[int]]:
word_set = set(words)
n = len(text)
# Trying i in order and then j in order gives the pairs already sorted.
return [[i, j] for i in range(n) for j in range(i, n) if text[i : j + 1] in word_set]