Index Pairs of a String - Problem

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).

Input & Output

Example 1 — Basic Case
$ Input: text = "thestoryofa", words = ["story","fleet","leetcode"]
Output: [[3,7]]
💡 Note: Only "story" appears in text starting at index 3 and ending at index 7: text[3...7] = "story"
Example 2 — Multiple Matches
$ Input: text = "ababa", words = ["ab","ba"]
Output: [[0,1],[1,2],[3,4]]
💡 Note: "ab" appears at [0,1] and "ba" appears at [1,2] and [3,4]. All pairs sorted by first coordinate, then second.
Example 3 — Overlapping Words
$ Input: text = "aaaa", words = ["aa","aaa"]
Output: [[0,1],[0,2],[1,2],[1,3],[2,3]]
💡 Note: "aa" appears at [0,1], [1,2], [2,3] and "aaa" appears at [0,2], [1,3]. Results sorted naturally.

Constraints

  • 1 ≤ text.length ≤ 100
  • 1 ≤ words.length ≤ 20
  • 1 ≤ words[i].length ≤ 50
  • text and words[i] consist of lowercase English letters only

Visualization

Tap to expand
Index Pairs of a StringInput Text: "ababa"ababa01234Target Words: ["ab", "ba"]abbaFound Matches:ab [0,1]ba [1,2]ba [3,4]Output: [[0,1], [1,2], [3,4]]Sorted by first coordinate, then second coordinate
Understanding the Visualization
1
Input
Text string and array of target words to find
2
Process
Check all substrings against word list
3
Output
Sorted array of [start, end] index pairs
Key Takeaway
🎯 Key Insight: Use efficient lookup structures (hash set or Trie) to avoid repeated linear searches through the words array
Asked in
Google 15 Amazon 12
12.5K Views
Medium Frequency
~15 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen