Index Pairs of a String in Python

Finding index pairs of substrings within a text is a common string matching problem. Given a text string and a list of words, we need to find all index pairs [i, j] where the substring text[i:j+1] matches any word in the list.

Problem Understanding

For example, with text "ababa" and words ["aba", "ab"], we find overlapping matches ?

  • "ab" at positions [0,1] and [2,3]
  • "aba" at positions [0,2] and [2,4]

Algorithm Steps

The approach uses nested loops to check all possible substrings ?

  1. Initialize an empty result list
  2. For each starting position i in the text
  3. For each ending position j from i+1 to end of text
  4. Check if substring text[i:j] exists in words list
  5. If found, add [i, j-1] to result (j-1 because we want inclusive end index)

Implementation

class Solution:
    def indexPairs(self, text, words):
        result = []
        for i in range(len(text)):
            for j in range(i+1, len(text)+1):
                if text[i:j] in words:
                    result.append([i, j-1])
        return result

# Test the solution
solution = Solution()
text = "ababa"
words = ["aba", "ab"]
result = solution.indexPairs(text, words)
print(f"Text: {text}")
print(f"Words: {words}")
print(f"Index pairs: {result}")
Text: ababa
Words: ['aba', 'ab']
Index pairs: [[0, 1], [0, 2], [2, 3], [2, 4]]

Step-by-Step Execution

Let's trace through the algorithm with our example ?

def indexPairsWithTrace(text, words):
    result = []
    print(f"Searching in text: '{text}'")
    print(f"Looking for words: {words}")
    print()
    
    for i in range(len(text)):
        for j in range(i+1, len(text)+1):
            substring = text[i:j]
            if substring in words:
                result.append([i, j-1])
                print(f"Found '{substring}' at positions [{i}, {j-1}]")
    
    return result

# Trace execution
result = indexPairsWithTrace("ababa", ["aba", "ab"])
print(f"\nFinal result: {result}")
Searching in text: 'ababa'
Looking for words: ['aba', 'ab']

Found 'ab' at positions [0, 1]
Found 'aba' at positions [0, 2]
Found 'ab' at positions [2, 3]
Found 'aba' at positions [2, 4]

Final result: [[0, 1], [0, 2], [2, 3], [2, 4]]

Time and Space Complexity

Complexity Value Explanation
Time O(n³) Nested loops O(n²) + substring creation O(n)
Space O(k) k is the number of matching pairs found

Alternative Example

# Test with different input
solution = Solution()
text = "thestoryofleetcoding"
words = ["story", "fleet", "leetcode"]
result = solution.indexPairs(text, words)

print(f"Text: '{text}'")
print(f"Words: {words}")
print(f"Index pairs: {result}")
Text: 'thestoryofleetcoding'
Words: ['story', 'fleet', 'leetcode']
Index pairs: [[3, 7], [9, 13]]

Conclusion

This brute force approach systematically checks all possible substrings against the word list. While simple to implement, it has O(n³) time complexity. For better performance with large inputs, consider using more advanced string matching algorithms like Trie or Aho-Corasick.

Updated on: 2026-03-25T08:07:34+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements