DSA Trie

Index Pairs of a String

Return all (start, end) index pairs where the substring exists in the dictionary — trie walk from each start.

Easy
Time O(N * L) Space O(D * L)
5 min read
trie strings

Problem#

Given a string text and a words list, return all pairs [i, j] such that text[i..j] is in words. Sort the result by i, then by j. This problem is an curriculum variant; LeetCode 1065 is similar.

Examples#

  • text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"][[3,7],[9,13],[10,17]].
  • text = "ababa", words = ["aba","ab"][[0,1],[0,2],[2,3],[2,4]].

Constraints#

  • 1 <= text.length <= 100, 1 <= words.length <= 20.

Hints#

Hint
Build a trie of words; from each starting index, walk the trie as long as children exist and collect every word end.

Approach#

Insert all words into a trie. For each starting index i in text, walk the trie following text[i], text[i+1], ... and emit [i, j] for every node marking a word end.

Solution#

Index Pairs of a String
class Solution {
struct Node {
Node* child[26]{};
bool isEnd = false;
};
void insert(Node* root, const string& w) {
Node* cur = root;
for (char c : w) {
int i = c - 'a';
if (!cur->child[i]) cur->child[i] = new Node();
cur = cur->child[i];
}
cur->isEnd = true;
}
public:
vector<vector<int>> indexPairs(string text, vector<string>& words) {
Node* root = new Node();
for (auto& w : words) insert(root, w);
vector<vector<int>> ans;
int n = text.size();
for (int i = 0; i < n; ++i) {
Node* cur = root;
for (int j = i; j < n; ++j) {
int idx = text[j] - 'a';
if (!cur->child[idx]) break;
cur = cur->child[idx];
if (cur->isEnd) ans.push_back({i, j});
}
}
return ans;
}
};

Editorial#

Each starting index produces at most one trie walk that terminates when the path leaves the dictionary, so total work is O(N * L) for L = max word length. Collecting matches along the walk (instead of after) catches both short and long words sharing prefixes — e.g., "ab" and "aba" rooted at the same index.

Complexity#

  • Time: O(N * L).
  • Space: O(D * L) for the trie.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.