Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find all possible substrings after deleting k characters in Python
Sometimes we need to find all possible substrings after deleting exactly k characters from a string. This means keeping n-k characters in their original order to form new substrings. Python provides multiple approaches to solve this problem efficiently.
Using Loops and Recursion
This approach uses recursion to generate all combinations by selecting characters at different positions. We track the start and end positions while building each substring ?
def letterCombinations(s, temp, start, end, index, k):
result = []
if index == k:
elem = ''.join(temp[:k])
result.append(elem)
return result
for i in range(start, end - k + index + 2):
temp[index] = s[i]
result.extend(letterCombinations(s, temp, i + 1, end, index + 1, k))
return result
stringA = 'Apple'
k = 1 # Delete 1 character, keep 4
temp = [''] * (len(stringA) - k)
start = 0
end = len(stringA) - 1
combinations = letterCombinations(stringA, temp, start, end, 0, len(stringA) - k)
result = set(combinations)
print(result)
{'Appe', 'Appl', 'Aple', 'pple'}
Using itertools.combinations
The itertools.combinations() function provides a cleaner approach by directly generating all possible character combinations of the desired length ?
from itertools import combinations stringA = 'Apple' k = 1 # Delete 1 character, keep 4 # Generate all combinations of (n-k) characters result = set([''.join(combo) for combo in combinations(stringA, len(stringA) - k)]) print(result)
{'Appe', 'Appl', 'Aple', 'pple'}
Example with Multiple Deletions
Here's how to delete more characters from a longer string ?
from itertools import combinations
stringA = 'Python'
k = 2 # Delete 2 characters, keep 4
result = set([''.join(combo) for combo in combinations(stringA, len(stringA) - k)])
print(f"Original: {stringA}")
print(f"Substrings after deleting {k} characters: {result}")
print(f"Total combinations: {len(result)}")
Original: Python
Substrings after deleting 2 characters: {'Pyhn', 'Pthn', 'Pyon', 'ython', 'Phon', 'Pthon', 'yhon', 'Pyton', 'Pyto', 'thon', 'ythn', 'Pton', 'Pyho', 'ytho', 'Ptho'}
Total combinations: 15
Comparison
| Method | Time Complexity | Code Length | Best For |
|---|---|---|---|
| Recursion | O(C(n,k)) | Long | Understanding the logic |
| itertools.combinations | O(C(n,k)) | Short | Production code |
Conclusion
Use itertools.combinations() for clean, readable code when finding substrings after deleting k characters. The recursive approach helps understand the underlying logic but is more verbose.
