Print all subsequences of a string in C++

In this problem, we are given a string and we have to print all the subsequences of the string. The substring generated is created by deleting the elements of the string but the order remains the same(i.e. Order cannot be changed).

Let’s take an example to understand the topic better −

Input: xyz
Output: x,y,z,xy,yz,xz,xyz

Explanation − In the above example, we can see the only characters are deleted to create substring. No, rearranging takes place.

There can be multiple methods to solve this problem, here we will discuss a few of them to understand methods.

One is by selecting elements of the string and eliminating a few to create a sequence. In this method, we will pick a few elements and delete the rest to create the substring.

Example

import java.util.*;
class Main{
   public static ArrayListsubStringSeq=new ArrayList();
   public static void main(String[] args) {
      String s="pqrs";
      System.out.println("All the substring found are :");
      findSubString(s,"");
      System.out.println(subStringSeq);
   }
   public static void findSubString(String s, String ans) {
      if(s.length()==0){
         subStringSeq.add(ans);
         return;
      }
      findSubString(s.substring(1),ans+s.charAt(0)) ;
      findSubString(s.substring(1),ans);
   }
}

Output

All the substring found are −

[pqrs, pqr, pqs, pq, prs, pr, ps, p, qrs, qr, qs, q, rs, r, s, ]

Another method could be iterating over the string and generate substring. And dropping characters of the sequence to generate substrings. Here, we will use a list to store the substrings. And check if the sequence found is already found or not.

Example

import java.util.HashSet;
public class Main{
   static HashSet subString = new HashSet();
   static void findSubString(String str){
      for (int i = 0; i  i; j--) {
            String sub_str = str.substring(i, j);
            if (!subString.contains(sub_str))
               subString.add(sub_str);
            for (int k = 1; k 

Output

The subsequence is

[rs, pq, qr, pr, qs, ps, prs, p, pqr, q, r, s, pqs, qrs, pqrs]

One more method can be fix characters and find substring. In this method we will fix elements of the string one by one and using these fixed characters, we will find the subsequence. Recursive calling of this method creates the required string subsequence.

Example

class Main {
   static void subString(String str, int n,
   int index, String curr){
      if (index == n){
         return;
      }
      System.out.print(curr + ", ");
      for (int i = index + 1; i 

Output

The subStrings are −

p, pq, pqr, pqrs, pqs, pr, prs, ps, q, qr, qrs, qs, r, rs, s
Updated on: 2020-01-17T10:41:28+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements