Given a string S of length N, the task is to find the lexicographically smallest K-length subsequence from the string S (where K < N).
Input: S = “bbcaab”, K = 3
Input: S = “aabdaabc”, K = 3
Naive Approach: The simplest approach is to generate all possible subsequences of length K from the given string and store all subsequences in a vector. Now, sort the vector and print the string at 0th position for lexicographically the smallest subsequence.
Time Complexity: O(2N)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea to use Stack Data Structure to keep the track of characters in increasing order, to get the lexicographically smallest subsequence. Follow the steps below to solve the problem:
- Initialize a stack, say answer, such that at any index of the string, the stack should contain the smallest K-length subsequence up to the current index.
- Traverse the string and perform the following steps:
- If the stack is empty, then push the current character into the stack.
- Otherwise, iterate until the current element of the string S[i] is less than the top element of the stack and keep popping from the stack to ensure that the size of the stack is at most K.
- If the size of the stack is less than K after the above step, then push the current character into the stack.
- After completing the above steps, print the characters stored in the stack in reverse order to obtain the resultant subsequence string.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
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.