Ctrl K

Dictionary Words in a Text

Easy
You are given a string text and a list of distinct words vocabulary. Find every place where a vocabulary word appears in text as a substring. Describe each occurrence as a pair [i, j]: the indices of its first and last letter (0-based, both ends inclusive). Occurrences may overlap or sit inside one another. Return the list of pairs sorted by i, and by j when the i values are equal.
Example 1
text="sunflower", vocabulary=["sun", "flow", "flower", "low"] → [[0, 2], [3, 6], [3, 8], [4, 6]]

"sun" spans 0–2, "flow" 3–6, "flower" 3–8, "low" 4–6. Pairs with the same start are ordered by their end.

Example 2
text="aaa", vocabulary=["aa", "b"] → [[0, 1], [1, 2]]

Occurrences may overlap: "aa" appears at position 0 and at position 1. "b" does not appear at all.

Constraints
  • 1 ≤ len(text) ≤ 100
  • 1 ≤ len(vocabulary) ≤ 20
  • 1 ≤ length of each word ≤ 50
  • All strings consist of lowercase English letters
  • The words in vocabulary are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNo Number Starts Another EasyDistinct Word Shorthands HardMost Searched Words MediumWord Grown Letter by Letter MediumWords Hidden in a Text Medium
loading Python…
Input
text="sunflower", vocabulary=["sun", "flow", "flower", "low"]
Expected
[[0, 2], [3, 6], [3, 8], [4, 6]]

Run checks the first 3 tests in your browser. Submit checks all 84 tests on the server, hidden ones included.