VOOZH about

URL: https://www.geeksforgeeks.org/dsa/subsequences-of-given-string-consisting-of-non-repeating-characters/

⇱ Subsequences of given string consisting of non-repeating characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subsequences of given string consisting of non-repeating characters

Last Updated : 23 Jul, 2025

Given a string str of length N, the task is to print all possible distinct subsequences of the string str which consists of non-repeating characters only.

Examples:

Input: str = "abac" 
Output: a ab abc ac b ba bac bc c 
Explanation: 
All possible distinct subsequences of the strings are { a, aa, aac, ab, aba, abac, abc, ac, b, ba, bac, bc, c } 
Therefore, the subsequences consisting non-repeating characters only are { a, ab, abc, ac, b, ba, bac, bc, c }

Input: str = "aaa" 
Output: a

Approach: The problem can be solved using Backtracking technique using the following recurrence relation:

FindSub(str, res, i) = { FindSub(str, res, i + 1), FindSub(str, res + str[i], i + 1) }
res = subsequence of the string 
i = index of a character in str 

Follow the steps below to solve the problem:

  • Initialize a Set, say sub, to store all possible subsequences consisting of non-repeating characters.
  • Initialize another Set, say ch, to check if a character is present in the subsequence or not.
  • Traverse the string and print all possible subsequences consisting of non-repeating characters only using the above recurrence relation.

Below is the implementation of the above approach:


Output: 
a ab abc ac b ba bac bc c

 

Time complexity: O(N * log(N) * 2N
Auxiliary Space O(N * 2N)

Comment
Article Tags:
Article Tags: