Print all Subsequences of a String in Python

A subsequence is a sequence derived from another sequence by deleting some characters without changing the order of remaining elements. For string "abc", subsequences include "", "a", "b", "c", "ab", "ac", "bc", "abc". Python offers both recursive and iterative approaches to generate all subsequences.

Understanding Subsequences

A subsequence maintains the relative order of characters from the original string while allowing deletions. For string "India", some subsequences are "", "I", "In", "Ind", "India". A string of length n has exactly 2n subsequences (including the empty string).

Recursive Approach

The recursive method uses the principle that each character can either be included or excluded from a subsequence ?

def get_all_subsequences(string):
    if len(string) == 0:
        return ['']
    
    first_char = string[0]
    remaining_subsequences = get_all_subsequences(string[1:])
    current_subsequences = []
    
    for subsequence in remaining_subsequences:
        current_subsequences.append(subsequence)
        current_subsequences.append(first_char + subsequence)
    
    return current_subsequences

# Test the function
input_string = 'abc'
subsequences = get_all_subsequences(input_string)
print("All subsequences:", subsequences)
print("Total count:", len(subsequences))
All subsequences: ['', 'c', 'b', 'bc', 'a', 'ac', 'ab', 'abc']
Total count: 8

Iterative Approach

The iterative method builds subsequences step by step, adding each new character to existing subsequences ?

def get_all_subsequences_iterative(string):
    subsequences = ['']
    
    for char in string:
        current_subsequences = []
        
        for subsequence in subsequences:
            current_subsequences.append(subsequence)
            current_subsequences.append(subsequence + char)
        
        subsequences = current_subsequences
    
    return subsequences

# Test the function
input_string = 'abc'
subsequences = get_all_subsequences_iterative(input_string)
print("All subsequences:", subsequences)
print("Total count:", len(subsequences))
All subsequences: ['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
Total count: 8

Comparison of Approaches

Aspect Recursive Iterative
Time Complexity O(n × 2n) O(n × 2n)
Space Complexity O(n × 2n) + O(n) stack O(n × 2n)
Memory Usage Higher (call stack) Lower (no recursion)
Readability More intuitive More efficient

Practical Example

Let's generate subsequences for a DNA sequence to understand pattern analysis ?

def analyze_dna_subsequences(dna_sequence):
    subsequences = get_all_subsequences_iterative(dna_sequence)
    
    # Count subsequences by length
    length_count = {}
    for subseq in subsequences:
        length = len(subseq)
        length_count[length] = length_count.get(length, 0) + 1
    
    print(f"DNA Sequence: {dna_sequence}")
    print(f"Total subsequences: {len(subsequences)}")
    print("Count by length:")
    for length, count in sorted(length_count.items()):
        print(f"  Length {length}: {count} subsequences")

# Analyze a short DNA sequence
analyze_dna_subsequences("ATCG")
DNA Sequence: ATCG
Total subsequences: 16
Count by length:
  Length 0: 1 subsequences
  Length 1: 4 subsequences
  Length 2: 6 subsequences
  Length 3: 4 subsequences
  Length 4: 1 subsequences

Common Use Cases

String Processing: Pattern matching and text analysis algorithms often need to examine all possible character combinations.

Bioinformatics: DNA sequence analysis requires generating subsequences to identify conserved regions and mutations.

Algorithm Design: Problems like longest common subsequence and dynamic programming solutions rely on subsequence generation.

Conclusion

Both recursive and iterative approaches generate all subsequences effectively, with the iterative method being more memory-efficient. Choose the recursive approach for clarity and the iterative approach for better performance with larger strings.

Updated on: 2026-03-27T09:45:20+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements