Print all subsequences of a string in Python
Last Updated :
25 Nov, 2024
Given a string s of size n (1 ≤ n ≤ 20), the task is to print all subsequences of string. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Examples:
Input: s = "abc"
Output: ["", "a", "b", "c", "ab", "ac", "bc", "abc"]
Explanation: All possible combinations of the characters in the string are returned, including the empty string.
Input: S = "ab"
Output: ["", "a", "b", "ab"]
Explanation: All subsequences of the string ab are returned in any order.
Using Recursion
The recursive approach works by considering two options for each character:
- Include the character in the current subsequence.
- Exclude the character from the current subsequence.
By recursively generating subsequences for all characters, we can obtain the complete set of subsequences.
Python
# Recursive function to generate subsequences.
def subseq_rec(idx, curr, s, res):
# Base case: If we've processed all characters,
# add current subsequence
if idx == len(s):
res.append(curr)
return
# Include current character in subsequence
subseq_rec(idx + 1, curr + s[idx], s, res)
# Exclude current character from subsequence
subseq_rec(idx + 1, curr, s, res)
# Wrapper function to generate all subsequences recursively.
def all_subseq_rec(s):
# List to store results
res = []
# Start recursion from index 0
subseq_rec(0, "", s, res)
return res
s = "abc"
print(all_subseq_rec(s))
Output['abc', 'ab', 'ac', 'a', 'bc', 'b', 'c', '']
Time Complexity: O(n * 2^n), where n is length of the string. At each step we make two recursive calls resulting in 2^n subsequences.
Auxiliary Space: O(2^n) for storing all subsequences and O(n) recursion stack.
Using Iterative Bit Masking
The iterative approach uses bit masking to generate all subsequences. Each bit in a number represents whether a character is included in the subsequence.
How it Works:
- For a string of length n there are 2^n subsets.
- Each number from 0 to 2^n - 1 represents a subset, where binary representation of number determines which characters are included in the subsequence.
- If the j-th bit is 1 then include the j-th character of string in subsequence.
Python
# Generate subsequences using bit masking.
def all_subseq(s):
n = len(s)
# List to store results
res = []
# Loop over all possible masks from 0 to 2^n - 1
for mask in range(1 << n):
# Current subsequence being formed
curr = ""
# Check each bit in mask
for i in range(n):
# If i-th bit is set, include s[i]
if mask & (1 << i):
curr += s[i]
# Add current subsequence to result list
res.append(curr)
return res
s = "abc"
print(all_subseq(s))
Output['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
Time Complexity: O(n * 2^n), where 2^n is the number of subsequences and n is the maximum length of each subsequence.
Auxiliary Space: O(2^n), as all subsequences are stored in a list.
Using Python's Built-in Libraries (Combinations)
Using itertools.combinations library we can generate all subsequences of lengths 0 to n.
Python
from itertools import combinations
# Generate subsequences using combinations from itertools.
def all_subseq(s):
# Start with the empty subsequence
res = [""]
# Generate combinations of lengths 1 to n
for r in range(1, len(s) + 1):
# Add all combinations of length r to result
res.extend([''.join(comb) for comb in combinations(s, r)])
return res
s = "abc"
print(all_subseq(s))
Output['', 'a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
Time Complexity: O(n * 2^n), as it generates all subsets.
Auxiliary Space: O(2^n), as all subsequences are stored.
Similar Reads
Print all subsequences of a string Given a string, we have to find out all its subsequences of it. A String is said to be a subsequence of another String, if it can be obtained by deleting 0 or more character without changing its order.Examples: Input : abOutput : "", "a", "b", "ab"Input : abcOutput : "", "a", "b", "c", "ab", "ac", "
12 min read
Print all subsequences of a string using ArrayList Given a string str, the task is to print all the sub-sequences of str. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.Examples: Input: str = "abc" Output: a b ab c ac bc abcInput: str = "geek"
8 min read
Print all subsequences of a string | Iterative Method Given a string s, print all possible subsequences of the given string in an iterative manner. We have already discussed Recursive method to print all subsequences of a string. Examples: Input : abc Output : a, b, c, ab, ac, bc, abc Input : aab Output : a, b, aa, ab, aab Approach 1 : Here, we discuss
15 min read
String Subsequence and Substring in Python Subsequence and Substring both are parts of the given String with some differences between them. Both of them are made using the characters in the given String only. The difference between them is that the Substring is the contiguous part of the string and the Subsequence is the non-contiguous part
5 min read
Python - Check if substring present in string The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check.Using in operatorThis
2 min read
How to Substring a String in Python A String is a collection of characters arranged in a particular order. A portion of a string is known as a substring. For instance, suppose we have the string "GeeksForGeeks". In that case, some of its substrings are "Geeks", "For", "eeks", and so on. This article will discuss how to substring a str
4 min read
Check if String Contains Substring in Python This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
8 min read
Subarray, Subsequence and Subsets in Python Algorithms and data manipulation are areas where it is important to grasp the ideas behind subarrays, subsequences as well as subsets. This article introduces the concepts of subarrays, subsequences along with subsets in Python. You will find out what these terms actually mean and how they differ fr
7 min read
Subsequence meaning in DSA A subsequence is defined as a sequence that can be derived from another string/sequence by deleting some or none of the elements without changing the order of the remaining elements. For example: Let's take "GeeksForGeeks", GeeksF will be a subsequence of "GeeksForGeeks". Example of SubsequencePrope
2 min read
Convert string to a list in Python Our task is to Convert string to a list in Python. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we'll explore these conversion techniques with simple examples. The most common way to convert a string into a list is
2 min read