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 Backtracing 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:
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to find all the subsequences of // the string with non-repeating characters void FindSub(set<string>& sub, set< char >& ch, string str, string res, int i) { // Base case if (i == str.length()) { // Insert current subsequence sub.insert(res); return ; } // If str[i] is not present // in the current subsequence if (!ch.count(str[i])) { // Insert str[i] into the set ch.insert(str[i]); // Insert str[i] into the // current subsequence res.push_back(str[i]); FindSub(sub, ch, str, res, i + 1); // Remove str[i] from // current subsequence res.pop_back(); // Remove str[i] from the set ch.erase(str[i]); } // Not including str[i] from // the current subsequence FindSub(sub, ch, str, res, i + 1); } // Utility function to print all subsequences // of string with non-repeating characters void printSubwithUniqueChar(string str, int N) { // Stores all possible subsequences // with non-repeating characters set<string> sub; // Stores subsequence with // non-repeating characters set< char > ch; FindSub(sub, ch, str, "" , 0); // Traverse all possible subsequences // containing non-repeating characters for ( auto subString : sub) { // Print subsequence cout << subString << " " ; } } // Driver Code int main() { string str = "abac" ; int N = str.length(); printSubwithUniqueChar(str, N); return 0; } |
a ab abc ac b ba bac bc c
Time complexity: O(N * log(N) * 2N)
Auxiliary Space O(N * 2N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.