Print all subsequences of a string in Python
Last Updated :
12 Jul, 2025
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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
TCP/IP Model The TCP/IP model is a framework that is used to model the communication in a network. It is mainly a collection of network protocols and organization of these protocols in different layers for modeling the network.It has four layers, Application, Transport, Network/Internet and Network Access.While
7 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read