Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Print all subsequences of a string | Iterative Method
Next article icon

Print all subsequences of a string in Python

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Using Recursion
  • Using Iterative Bit Masking
  • Using Python Built-in Libraries (Combinations)

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.



Next Article
Print all subsequences of a string | Iterative Method
author
kartik
Improve
Article Tags :
  • Python
  • Python list-programs
  • subsequence
Practice Tags :
  • python

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
  • Print All Sublists of a List in Python
    We are given a list and our task is to generate all possible sublists (continuous or non-continuous subsequences). For example: a = [1, 2, 3] The possible sublists are: [[], [1], [2], [3], [1, 2], [2, 3], [1, 3], [1, 2, 3]] Using itertools.combinationsitertools.combinations() generates all possible
    3 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
  • Check if given String can be split only into subsequences ABC
    Given a string S of length N where each character of the string is either 'A', 'B' or 'C'. The task is to find if is it possible to split the string into subsequences "ABC". If it is possible to split then print "Yes". Otherwise, print "No". Examples: Input: S = "ABABCC"Output: YesExplanation:One of
    12 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences