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
Program to generate all possible strings by taking the choices in python
When working with strings that contain choices in square brackets, we need to generate all possible combinations. For example, [d|t|l]im[e|s] represents multiple possible strings where we can choose from the options within brackets.
The pattern [a|b|c] means we can choose either a, b, or c. Our task is to find all possible strings by making these choices.
Example
For the input s = "[d|t|l]im[e|s]", the output will be ['dime', 'dims', 'lime', 'lims', 'time', 'tims'].
Algorithm
We'll use a recursive approach with backtracking ?
- If the string is empty, return a list with an empty string
- Use a helper function to recursively process each position
- When we find
[, extract all options between[and] - Try each option and continue recursively
- Use backtracking to explore all possibilities
Implementation
class Solution:
def solve(self, s):
if not s:
return [""]
n = len(s)
seq = []
res = []
def helper(pos):
if pos == n:
res.append("".join(seq))
else:
if "[" in s[pos:]:
start = pos + s[pos:].index("[")
end = pos + s[pos:].index("]")
# Add the part before the bracket
for option in s[start + 1 : end].split("|"):
seq.append(s[pos:start])
seq.append(option)
helper(end + 1)
seq.pop()
seq.pop()
else:
# No more brackets, add remaining string
seq.append(s[pos:])
helper(n)
seq.pop()
helper(0)
return sorted(res)
# Test the solution
solution = Solution()
s = "[d|t|l]im[e|s]"
result = solution.solve(s)
print(result)
The output of the above code is ?
['dime', 'dims', 'lime', 'lims', 'time', 'tims']
How It Works
The algorithm works by:
-
Finding brackets: When we encounter
[, we locate the matching] -
Extracting options: Split the content between brackets by
|to get all choices - Backtracking: For each option, we add it to our current sequence, recurse, then remove it to try the next option
- Building result: When we reach the end of the string, we join all parts in our sequence
Another Example
solution = Solution()
# Example with different choices
test_cases = [
"a[b|c]d",
"[x|y]z[1|2]",
"hello", # No brackets
"[a|b|c]" # Only brackets
]
for test in test_cases:
result = solution.solve(test)
print(f"Input: '{test}' ? Output: {result}")
The output of the above code is ?
Input: 'a[b|c]d' ? Output: ['abd', 'acd'] Input: '[x|y]z[1|2]' ? Output: ['xz1', 'xz2', 'yz1', 'yz2'] Input: 'hello' ? Output: ['hello'] Input: '[a|b|c]' ? Output: ['a', 'b', 'c']
Time Complexity
The time complexity is O(k^n) where k is the average number of choices per bracket and n is the number of brackets. This is because we generate all possible combinations.
Conclusion
This recursive backtracking approach efficiently generates all possible strings from bracket choices. The algorithm handles any number of brackets and choices, returning results in sorted order for consistency.
