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],[2,3],[3,4]]
💡 Note: "ab" appears at [0,1] and [2,3], "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 String Hash Set Optimization Approach INPUT text = "thestoryofa" t 0 h 1 e 2 s 3 t 4 o 5 r 6 y 7 o 8 f 9 a 10 words array: "story" "fleet" "leetcode" HashSet of Words: {"story", "fleet", "leetcode"} O(1) lookup time Summary: text length: 11 words count: 3 ALGORITHM STEPS 1 Build Hash Set Add all words to HashSet 2 Iterate All Starts For i from 0 to len(text)-1 3 Check Substrings For j from i to len(text)-1 4 Match in HashSet? If found, add [i,j] to result Checking Process: i=3: "s" not in set i=3: "st" not in set i=3: "sto" not in set i=3: "stor" not in set i=3: "story" FOUND! Result: [3, 7] FINAL RESULT Found Index Pairs: [[3, 7]] Substring Match: text[3...7] = "story" "story" exists in words OK - Valid match! Words not found in text: "fleet" "leetcode" Time: O(n^2 * m) Space: O(k) for HashSet Key Insight: Using a HashSet allows O(1) lookup for each substring, avoiding repeated linear searches through the words array. We generate all possible substrings text[i...j] and check if each exists in the set. Results are naturally sorted by iterating i then j in ascending order. TutorialsPoint - Index Pairs of a String | Hash Set Optimization
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