Index Pairs of a String — LeetCode 1065 Python Solution

EasyLeetCode PremiumTrieArrayStringSorting
Problem
#1065
Pattern
Trie
Reading time
2 min

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

Example

Input
text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
Output
[[3,7],[9,13],[10,17]]

Python solution

Python
class Solution:
    def indexPairs(self, text: str, words: List[str]) -> List[List[int]]:
        words = set(words)
        n = len(text)
        return [
            [i, j] for i in range(n) for j in range(i, n) if text[i : j + 1] in words
        ]

Complexity

MeasureComplexity
TimeO(total characters)
SpaceO(total characters) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 1065. Index Pairs of a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Trie.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1065. Index Pairs of a String?
LeetCode 1065. Index Pairs of a String is rated Easy on LeetCode.
What is the time complexity of LeetCode 1065. Index Pairs of a String?
The Python solution on this page runs in O(total characters).
What is the space complexity of LeetCode 1065. Index Pairs of a String?
The Python solution on this page uses O(total characters) auxiliary space.
What topics does LeetCode 1065. Index Pairs of a String cover?
LeetCode 1065. Index Pairs of a String is tagged Trie, Array, String and Sorting on LeetCode.
Is LeetCode 1065. Index Pairs of a String a premium problem?
Yes. LeetCode 1065. Index Pairs of a String is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview