Generating distinct subsequences of a given string in lexicographic order

07 Jul, 2022
Given a string s, make a list of all possible combinations of letters of a given string S. If there are two strings with the same set of characters, print the lexicographically smallest arrangement of the two stringsFor string abc, the list in lexicographic order subsequences are, a ab abc ac b bc cExamples:  
Input : s = "ab"
Output : a ab b

Input  : xyzx
Output : x xx xy xyx xyz xyzx xz xzx y
         yx yz yzx z zx
 
The idea is to use a set (which is implemented using self balancing BST) to store subsequences so that duplicates can be tested.To generate all subsequences, we one by one remove every character and recur for remaining string.  
C++
Java
Python 3
C#
Javascript
// C++ program to print all distinct subsequences// of a string.#include <bits/stdc++.h>using namespace std; // Finds and stores result in st for a given// string s.void generate(set<string>& st, string s){    if (s.size() == 0)        return;     // If current string is not already present.    if (st.find(s) == st.end()) {        st.insert(s);         // Traverse current string, one by one        // remove every character and recur.        for (int i = 0; i < s.size(); i++) {            string t = s;            t.erase(i, 1);            generate(st, t);        }    }    return;} // Driver codeint main(){    string s = "xyz";    set<string> st;    set<string>::iterator it;    generate(st, s);    for (auto it = st.begin(); it != st.end(); it++)        cout << *it << endl;    return 0;}
// Java program to print all distinct subsequences// of a string.import java.util.*; class GFG {     // Finds and stores result in st for a given    // string s.    static void generate(Set<String> st, String s)    {        if (s.length() == 0) {            return;        }         // If current string is not already present.        if (!st.contains(s)) {            st.add(s);             // Traverse current string, one by one            // remove every character and recur.            for (int i = 0; i < s.length(); i++) {                String t = s;                t = t.substring(0, i) + t.substring(i + 1);                generate(st, t);            }        }        return;    }     // Driver code    public static void main(String args[])    {        String s = "xyz";        TreeSet<String> st = new TreeSet<>();        generate(st, s);        for (String str : st) {            System.out.println(str);        }    }} // This code has been contributed by 29AjayKumar// modified by rahul_107
# Python program to print all distinct# subsequences of a string. # Finds and stores result in st for a given# string s.def generate(st, s):    if len(s) == 0:        return     # If current string is not already present.    if s not in st:        st.add(s)         # Traverse current string, one by one        # remove every character and recur.        for i in range(len(s)):            t = list(s).copy()            t.remove(s[i])            t = ''.join(t)            generate(st, t)     return  # Driver Codeif __name__ == "__main__":    s = "xyz"    st = set()    generate(st, s)    for i in st:        print(i) # This code is contributed by# sanjeev2552
// C# program to print all distinct subsequences// of a string.using System;using System.Collections.Generic; class GFG {     // Finds and stores result in st for a given    // string s.    static void generate(HashSet<String> st, String s)    {        if (s.Length == 0) {            return;        }         // If current string is not already present.        if (!st.Contains(s)) {            st.Add(s);             // Traverse current string, one by one            // remove every character and recur.            for (int i = 0; i < s.Length; i++) {                String t = s;                t = t.Substring(0, i) + t.Substring(i + 1);                generate(st, t);            }        }        return;    }     // Driver code    public static void Main(String[] args)    {        String s = "xyz";        HashSet<String> st = new HashSet<String>();        generate(st, s);        foreach(String str in st)        {            Console.WriteLine(str);        }    }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript program to print// all distinct subsequences// of a string. // Finds and stores result in st for a given// string s.function generate(st,s){    if (s.length == 0)        return st;     // If current string is not already present.    if (!st.has(s)) {        st.add(s);        // Traverse current string, one by one        // remove every character and recur.        for (let i = 0; i < s.length; i++) {            let t = s;            t = t.substr(0, i) + t.substr(i + 1);            st = generate(st, t);        }    }    return st;} // Driver codelet s = "xyz"; let st = new Set();st = generate(st, s); let str = '';console.log(st)for(item of st.values())    str += item + '<br> '     document.write(str); </script>
Output:  
x
xy
xyz
xz
y
yz
z
Time Complexity: O(nn)
Auxiliary Space: O(n)
This article is contributed by Aarti_Rathi and SANDEEP GAUR MNNIT. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
29AjayKumar
princiraj1992
sanjeev2552
rahul_107
rohitsingh07052
adi1212
lexicographic-ordering
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Convert string to char array in C++
Check whether two strings are anagram of each other