VOOZH about

URL: https://www.geeksforgeeks.org/python/print-all-subsequences-of-a-string-in-python/

⇱ Print all subsequences of a string in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.


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.

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.


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.

Comment