There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:

import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]

If you want to find overlapping matches, lookahead will do that:

[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]

If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:

search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]

re.finditer returns a generator, so you could change the [] in the above to () to get a generator instead of a list which will be more efficient if you're only iterating through the results once.

Answer from moinudin on Stack Overflow
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ count-complete-substrings
Count Complete Substrings - LeetCode
Can you solve this real interview question? Count Complete Substrings - You are given a string word and an integer k. A substring s of word is complete if: * Each character in s occurs exactly k times.
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ maximum-number-of-occurrences-of-a-substring
Maximum Number of Occurrences of a Substring - LeetCode
Maximum Number of Occurrences of a Substring - Given a string s, return the maximum number of occurrences of any substring under the following rules: * The number of unique characters in the substring must be less than or equal to maxLetters.
๐ŸŒ
AlgoMonster
algo.monster โ€บ liteproblems โ€บ 1910
1910. Remove All Occurrences of a Substring - In-Depth Explanation
In-depth solution and explanation for LeetCode 1910. Remove All Occurrences of a Substring in Python, Java, C++ and more. Intuitions, example walk through, and complexity analysis. Better than official and forum solutions.
๐ŸŒ
Reddit
reddit.com โ€บ r/leetcode โ€บ optimized way to find all substrings/subsets/subarrays
r/leetcode on Reddit: Optimized way to find all substrings/subsets/subarrays
August 29, 2024 -

Hi! This is entirely based on a pattern in LeetCode problems, but if I need to find ALL substrings/subsets/subarrays of a string/array, is there a way I can do it in less than O(n^2) time complexity? Thank you!

Top answer
1 of 2
2
Depends on which subarrays you want to find. All of them? Just do 2 for loops. Ones with some "maximum size" criterion like "at most 2 distinct values"? Maybe something like sliding windows. Want to match a specific word? There's some string algorithms for that that are better than O(len(word)*len(bigstring)). Want to find matches with a set of words? Probably more string specific algorithms. Want to just count the subarrays of a certain type? Dynamic programming or something similar to prefix sum might help. In general, but especially with dp, it might help to try and group all the subarrays by their ending index or by their starting index. It helps recognizing that every subarray ending at index i is a subarray ending at index i-1 with arr[i] appended at the end or arr[i] itself or possibly the empty subarray if you count that. Want to find something like all intervals whose sum is a multiple of k? Try computing the prefix sums mod k. If i and j have the same prefix sum mod k (like both 2 mod 5) then the subarray from i to j has a sum that is a multiple of k. Want to do something like find the min value or something of each subarray and then add them up? Maybe use monotonic stack and summarize the results like the min values of subarrays ending at index i are (3 subarrays with 2, 5 subarrays with 4, 9 subarrays with 8). When you want to figure out what the min values are for at index i+1, and say arr[i+1] is 3, then pop off some larger values and now your summary of the mins is (3 subarrays with 2, 1(index i+1) +5+9 subarrays with minimum of 3) Probably lots more dp and/or problems where you want to add up some f(subarray) for each subarray. Subsets is very wide topic but might be greedy or dp. Subsequences is also very wide topic but might be dp or greedy.
2 of 2
1
One more trick: If you have some function f such that f(subarray) = some number and you want to make make queries about like the sum or min or max of f of each subarray within the subarray arr[i:j] try: dp1[i][j] = f( arr[i:j] ) \ this might be quicker to compute with dp or something dp2[i][j] = max( dp2[i+1][j], dp2[i][j-1], dp1[i][j] ) You either find the best answer as the entire subarray or the first element of the subarray isn't in the best answer so dp2[i+1][j] or the best answer doesnt use the last element so dp2[i][j-1].
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ find-indices-of-all-occurrence-of-one-string-in-other
Print all occurrences of a string as a substring in another string - GeeksforGeeks
July 11, 2025 - This approach finds the first occurrence of the substring using find() with the starting position set to 0, and stores the index of the occurrence in the pos variable of type size_t.
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ string-matching-in-an-array
String Matching in an Array - LeetCode
Can you solve this real interview question? String Matching in an Array - Given an array of string words, return all strings in words that are a substring of another word. You can return the answer in any order.
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @cyberseize โ€บ leetcode-1910-remove-all-occurrences-of-a-substring-8c1c7e58a83f
LeetCode 1910: Remove All Occurrences of a Substring | by Nikhil Jain | Medium
February 11, 2025 - While a simple approach might use stringโ€™s built-in methods like indexOf() and substring(), a more efficient solution can be achieved using the Knuth-Morris-Pratt (KMP) pattern matching algorithm combined with a stack-based approach.
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ find-and-replace-in-string
Find And Replace in String - LeetCode
Can you solve this real interview question? Find And Replace in String - You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k. To complete the ith replacement operation: 1. Check if the substring sources[i] occurs at index indices[i] in the original string s. 2. If it does not occur, do nothing.
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ substring-matching-pattern
Substring Matching Pattern - LeetCode
Can you solve this real interview question? Substring Matching Pattern - You are given a string s and a pattern string p, where p contains exactly one '*' character. The '*' in p can be replaced with any sequence of zero or more characters. Return true if p can be made a substring of s, and ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-all-occurrences-of-substring-in-string
Python - All occurrences of substring in string - GeeksforGeeks
July 12, 2025 - Track positions: Each found position ... for subsequent occurrences. List comprehension with range() can be used to generate all starting positions of a substring by iterating over the string indices....
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ number-of-strings-that-appear-as-substrings-in-word
Number of Strings That Appear as Substrings in Word - LeetCode
Can you solve this real interview question? Number of Strings That Appear as Substrings in Word - Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word. A substring is a contiguous sequence of characters within a string.
๐ŸŒ
PythonForBeginners.com
pythonforbeginners.com โ€บ home โ€บ find all occurrences of a substring in a string in python
Find All Occurrences of a Substring in a String in Python - PythonForBeginners.com
June 29, 2022 - This is due to the reason that the find() method returns the start index of a substring if it is found in the string. Then, we will move to the next execution of the for loop. If the find() method returns -1, we will move to the next execution of the for loop.
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ remove-all-occurrences-of-a-substring
Remove All Occurrences of a Substring - LeetCode
Remove All Occurrences of a Substring - Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: * Find the leftmost occurrence of the substring part and remove it from s. Return ...
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ find-the-index-of-the-first-occurrence-in-a-string
Find the Index of the First Occurrence in a String - LeetCode
Can you solve this real interview question? Find the Index of the First Occurrence in a String - Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "sadbutsad", needle = "sad" Output: 0 Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. Example 2: Input: haystack = "leetcode", needle = "leeto" Output: -1 Explanation: "leeto" did not occur in "leetcode", so we return -1. Constraints: * 1
๐ŸŒ
Medium
machine-learning-made-simple.medium.com โ€บ problem-2-find-substring-occurrences-microsoft-6ad48d9bdb41
Problem 2: Find Substring Occurrences[Microsoft] | by Devansh | Medium
October 21, 2023 - Luckily, there is hashing. Furthermore, since we are sliding across a string, we donโ€™t need to rehash from scratch. We just need to drop the leftmost character value from the hash and add the value created by the rightmost value.
๐ŸŒ
GitHub
gist.github.com โ€บ SuryaPratapK โ€บ ccbcee7b96ce00ee0cd4854bb1b3e098
Remove All Occurrences of a Substring | Leetcode 1910 ยท GitHub
Remove All Occurrences of a Substring | Leetcode 1910 ยท This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.