Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Recursion & Backtracking

All Subsequences in Lexicographic Order

Easy · Recursion & Backtracking · Asked at Amazon, Microsoft, TCS, Infosys

Print every distinct non-empty subsequence of the string, in lexicographic (dictionary) order, one per line.

Input

A single line with the string (lowercase letters).

Output

The distinct subsequences in lexicographic order.

Constraints

Recursion: for each position, either take the character or skip it — 2^n choices. Put the results in a set (to remove duplicates) and sort them.

Example 1

Input

abc

Output

a
ab
abc
ac
b
bc
c

Example 2

Input

aab

Output

a
aa
aab
ab
b

Hints

  1. Each character is either taken or skipped: 2^n subsequences in total.
  2. Repeated letters can create the same subsequence twice — keep them in a set.
  3. Sort the set at the end.

Approach

Recurse over the positions, carrying the subsequence built so far; at each position branch into "take" and "skip". At the end of the string, insert the (non-empty) subsequence into a set. With n ≤ 10 there are at most 1023 of them. Print the set in sorted order (std::set and TreeSet are already sorted).

Complexity: O(2^n · n log) time · O(2^n · n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

string s;
set<string> result;

void go(int i, string &cur) {
    if (i == (int) s.size()) {
        if (!cur.empty()) result.insert(cur);
        return;
    }
    cur.push_back(s[i]);
    go(i + 1, cur);
    cur.pop_back();
    go(i + 1, cur);
}

int main() {
    cin >> s;
    string cur;
    go(0, cur);
    for (auto &x : result) cout << x << "\n";
    return 0;
}

Python solution

s = input().strip()
result = set()


def go(i, cur):
    if i == len(s):
        if cur:
            result.add(cur)
        return
    go(i + 1, cur + s[i])
    go(i + 1, cur)


go(0, "")
print("\n".join(sorted(result)))

Java solution

import java.util.*;

public class Main {
    static String s;
    static TreeSet<String> result = new TreeSet<>();

    static void go(int i, StringBuilder cur) {
        if (i == s.length()) {
            if (cur.length() > 0) result.add(cur.toString());
            return;
        }
        cur.append(s.charAt(i));
        go(i + 1, cur);
        cur.deleteCharAt(cur.length() - 1);
        go(i + 1, cur);
    }

    public static void main(String[] args) {
        s = new Scanner(System.in).next();
        go(0, new StringBuilder());
        StringBuilder sb = new StringBuilder();
        for (String x : result) sb.append(x).append('\n');
        System.out.print(sb);
    }
}

Solve All Subsequences in Lexicographic Order online · All practice problems