Print all Subsequences of a string

Pattern: Subsets

medium

A subsequence keeps some characters in their original order. Take or skip each character in turn; every path through those choices spells one subsequence. Leave out the empty one.

The problem

Given a string, return all of its non-empty subsequences: strings made by deleting some characters (possibly none) and keeping the rest in order. For example, "abc" gives a, ab, abc, ac, b, bc and c. If letters repeat, equal subsequences from different positions are each listed, so "aa" gives a, a and aa.

The link above is a GeeksforGeeks article. The function name allSubsequences and the rule about repeats are this guide's own. The tests compare the answers after sorting.

Think first

  • How is a subsequence different from a substring?
  • How many subsequences does a string of length n have?
  • Which one should be left out?

Hints

    Brute force, and why it fails

    Loop over all 2ⁿ bit masks and build the string for each: the same O(2ⁿ × n), written without recursion. Both are optimal, since the output has 2ⁿ - 1 strings.

    The key insight

    Subsequences of a string are subsets of its positions. The take-or-skip recursion from Subsets lists them in the same way.

    Dry run

    a0 
    b1 
    c2 

    s = abc. At each character, choose take or skip.

    Step 1 of 4

    The plan

    function build(i, cur):
        if i == n:
            if cur is not empty: record cur
            return
        build(i + 1, cur + s[i])
        build(i + 1, cur)
    build(0, "")
    

    Complexity

    Time
    O(2ⁿ × n)
    Space
    O(n)

    2ⁿ - 1 strings of up to n characters. The recursion is n deep.

    Edge cases

    • One character: just itself.
    • Repeated letters: equal subsequences appear more than once.
    • Long strings: the output doubles with each character.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<String> allSubsequences(String s) {
            List<String> out = new ArrayList<>();
            build(s, 0, new StringBuilder(), out);
            return out;
        }
    
        private void build(String s, int i, StringBuilder cur, List<String> out) {
            if (i == s.length()) {
                if (cur.length() > 0) out.add(cur.toString());   // skip the empty subsequence
                return;
            }
            cur.append(s.charAt(i));                        // take s[i]
            build(s, i + 1, cur, out);
            cur.deleteCharAt(cur.length() - 1);             // or skip it
            build(s, i + 1, cur, out);
        }
    }

    C++

    class Solution {
    public:
        vector<string> allSubsequences(string s) {
            vector<string> out;
            string cur;
            build(s, 0, cur, out);
            return out;
        }
    
        void build(const string& s, size_t i, string& cur, vector<string>& out) {
            if (i == s.size()) {
                if (!cur.empty()) out.push_back(cur);       // skip the empty subsequence
                return;
            }
            cur.push_back(s[i]);                            // take s[i]
            build(s, i + 1, cur, out);
            cur.pop_back();                                 // or skip it
            build(s, i + 1, cur, out);
        }
    };

    Python

    class Solution:
        def allSubsequences(self, s: str) -> list[str]:
            out = []
    
            def build(i: int, cur: list) -> None:
                if i == len(s):
                    if cur:
                        out.append("".join(cur))    # skip the empty subsequence
                    return
                cur.append(s[i])                    # take s[i]
                build(i + 1, cur)
                cur.pop()                           # or skip it
                build(i + 1, cur)
    
            build(0, [])
            return out

    Common mistakes

    • Including the empty string.
    • Listing substrings only, which misses ones like ac.
    • Changing the order of characters.

    Similar problems