Print all subsequences of a strin

Given a string, we have to find out all subsequences of it. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order.


Input : abc
Output : a, b, c, ab, bc, ac, abc

Input : aaa
Output : a, aa, aaa

Explanation :

Step 1: Iterate over the entire String
Step 2: Iterate from the end of string 
        in order to generate different substring
        add the subtring to the list
Step 3: Drop kth character from the substring obtained 
        from above to generate different subsequence.
Step 4: if the subsequence is not in the list then recur.

Below is the implementation of the approach.

// Java Program to print all subsequence of a
// given string.
import java.util.HashSet;
public class Subsequence {
    // set to store all the subsequences
    static HashSet<String> st = new HashSet<>();
    // It computes all the subsequence of an string
    static void subsequence(String str)
        // iterate over the entire string
        for (int i = 0; i < str.length(); i++) {
            // iterate from the end of the string
            // to generate substrings
            for (int j = str.length(); j > i; j--) {
                String sub_str = str.substring(i, j);
                if (!st.contains(sub_str))
                // drop kth character in the substring
                // and if its not in the set then recur
                for (int k = 1; k < sub_str.length() - 1; k++) {
                    StringBuffer sb = new StringBuffer(sub_str);
                    // drop character from the string
                    if (!st.contains(sb))
    // Driver code
    public static void main(String[] args)
        String s = "aabc";


[aa, a, ab, bc, ac, b, aac, abc, c, aab, aabc]

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at #techcodebit #google #microsoft #facebook #interview portal #jobplacements



Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar