Skip to content
Related Articles

Related Articles

Improve Article

Lexicographically smallest K-length subsequence from a given string

  • Difficulty Level : Medium
  • Last Updated : 26 May, 2021
Geek Week

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). 

Examples:

Input: S = “bbcaab”, K = 3
Output: “aab”

Input: S = “aabdaabc”, K = 3
Output: “aaa”

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 is Stack Data Structure to keep track of characters in increasing order, to get the lexicographically smallest subsequence. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find lexicographically
// smallest subsequence of size K
void smallestSubsequence(string& S, int K)
{
    // Length of string
    int N = S.size();
 
    // Stores the minimum subsequence
    stack<char> answer;
 
    // Traverse the string S
    for (int i = 0; i < N; ++i) {
 
        // If the stack is empty
        if (answer.empty()) {
            answer.push(S[i]);
        }
        else {
 
            // Iterate till the current
            // character is less than the
            // the character at the top of stack
            while ((!answer.empty())
                   && (S[i] < answer.top())
 
                   // Check if there are enough
                   // characters remaining
                   // to obtain length K
                   && (answer.size() - 1 + N - i >= K)) {
                answer.pop();
            }
 
            // If stack size is < K
            if (answer.empty() || answer.size() < K) {
 
                // Push the current
                // character into it
                answer.push(S[i]);
            }
        }
    }
 
    // Stores the resultant string
    string ret;
 
    // Iterate until stack is empty
    while (!answer.empty()) {
        ret.push_back(answer.top());
        answer.pop();
    }
 
    // Reverse the string
    reverse(ret.begin(), ret.end());
 
    // Print the string
    cout << ret;
}
 
// Driver Code
int main()
{
    string S = "aabdaabc";
    int K = 3;
    smallestSubsequence(S, K);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to find lexicographically
  // smallest subsequence of size K
  static void smallestSubsequence(char []S, int K)
  {
 
    // Length of String
    int N = S.length;
 
    // Stores the minimum subsequence
    Stack<Character> answer = new Stack<>();
 
    // Traverse the String S
    for (int i = 0; i < N; ++i) {
 
      // If the stack is empty
      if (answer.isEmpty()) {
        answer.add(S[i]);
      }
      else {
 
        // Iterate till the current
        // character is less than the
        // the character at the top of stack
        while ((!answer.isEmpty())
               && (S[i] < answer.peek())
 
               // Check if there are enough
               // characters remaining
               // to obtain length K
               && (answer.size() - 1 + N - i >= K)) {
          answer.pop();
        }
 
        // If stack size is < K
        if (answer.isEmpty() || answer.size() < K) {
 
          // Push the current
          // character into it
          answer.add(S[i]);
        }
      }
    }
 
    // Stores the resultant String
    String ret="";
 
    // Iterate until stack is empty
    while (!answer.isEmpty()) {
      ret+=(answer.peek());
      answer.pop();
    }
 
    // Reverse the String
    ret = reverse(ret);
 
    // Print the String
    System.out.print(ret);
  }
  static String reverse(String input) {
    char[] a = input.toCharArray();
    int l, r = a.length - 1;
    for (l = 0; l < r; l++, r--) {
      char temp = a[l];
      a[l] = a[r];
      a[r] = temp;
    }
    return String.valueOf(a);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String S = "aabdaabc";
    int K = 3;
    smallestSubsequence(S.toCharArray(), K);
  }
}
 
// This code is contributed by shikhasingrajput

Python3




# CPP program for the above approach
 
# Function to find lexicographically
# smallest subsequence of size K
def smallestSubsequence(S, K):
   
    # Length of string
    N = len(S)
 
    # Stores the minimum subsequence
    answer = []
 
    # Traverse the string S
    for i in range(N):
       
        # If the stack is empty
        if (len(answer) == 0):
            answer.append(S[i])
        else:
           
            # Iterate till the current
            # character is less than the
            # the character at the top of stack
            while (len(answer) > 0 and (S[i] < answer[len(answer) - 1]) and (len(answer) - 1 + N - i >= K)):
                answer = answer[:-1]
 
            # If stack size is < K
            if (len(answer) == 0 or len(answer) < K):
               
                # Push the current
                # character into it
                answer.append(S[i])
 
    # Stores the resultant string
    ret = []
 
    # Iterate until stack is empty
    while (len(answer) > 0):
        ret.append(answer[len(answer) - 1])
        answer = answer[:-1]
 
    # Reverse the string
    ret = ret[::-1]
    ret = ''.join(ret)
     
    # Print the string
    print(ret)
 
# Driver Code
if __name__ == '__main__':
    S = "aabdaabc"
    K = 3
    smallestSubsequence(S, K)
     
    # This code is contributed by SURENDRA_GANGWAR.

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Function to find lexicographically
  // smallest subsequence of size K
  static void smallestSubsequence(char []S, int K)
  {
 
    // Length of String
    int N = S.Length;
 
    // Stores the minimum subsequence
    Stack<char> answer = new Stack<char>();
 
    // Traverse the String S
    for (int i = 0; i < N; ++i) {
 
      // If the stack is empty
      if (answer.Count==0) {
        answer.Push(S[i]);
      }
      else {
 
        // Iterate till the current
        // character is less than the
        // the character at the top of stack
        while ((answer.Count!=0)
               && (S[i] < answer.Peek())
 
               // Check if there are enough
               // characters remaining
               // to obtain length K
               && (answer.Count - 1 + N - i >= K)) {
          answer.Pop();
        }
 
        // If stack size is < K
        if (answer.Count==0 || answer.Count < K) {
 
          // Push the current
          // character into it
          answer.Push(S[i]);
        }
      }
    }
 
    // Stores the resultant String
    String ret="";
 
    // Iterate until stack is empty
    while (answer.Count!=0) {
      ret+=(answer.Peek());
      answer.Pop();
    }
 
    // Reverse the String
    ret = reverse(ret);
 
    // Print the String
    Console.Write(ret);
  }
  static String reverse(String input) {
    char[] a = input.ToCharArray();
    int l, r = a.Length - 1;
    for (l = 0; l < r; l++, r--) {
      char temp = a[l];
      a[l] = a[r];
      a[r] = temp;
    }
    return String.Join("",a);
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    String S = "aabdaabc";
    int K = 3;
    smallestSubsequence(S.ToCharArray(), K);
  }
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
//Javascript  program for the above approach
 
//function for reverse
function reverse(input) {
    a = input;
    var l, r = a.length - 1;
    for (l = 0; l < r; l++, r--) {
      var temp = a[l];
      a[l] = a[r];
      a[r] = temp;
    }
    return a;
  }
 
 
// Function to find lexicographically
// smallest subsequence of size K
function smallestSubsequence(S, K)
{
    // Length of string
    var N = S.length;
 
    // Stores the minimum subsequence
    answer = [];
 
    // Traverse the string S
    for (var i = 0; i < N; ++i) {
 
        // If the stack is empty
        if (answer.length==0) {
            answer.push(S[i]);
        }
        else {
 
            // Iterate till the current
            // character is less than the
            // the character at the top of stack
            while ((answer.length != 0) && (S[i] < answer[answer.length-1])
 
                   // Check if there are enough
                   // characters remaining
                   // to obtain length K
                   && (answer.length - 1 + N - i >= K)) {
                answer.pop();
            }
 
            // If stack size is < K
            if (answer.length==0 || answer.length < K) {
 
                // Push the current
                // character into it
                answer.push(S[i]);
            }
        }
    }
 
    // Stores the resultant string
    var ret = [];
 
    // Iterate until stack is empty
    while (answer.length != 0) {
        ret += answer[answer.length -1];
        answer.pop();
    }
 
    // Reverse the string
    reverse(ret);
 
    // Print the string
       document.write(ret);
}
 
 
 
var S = "aabdaabc";
var K = 3;
    smallestSubsequence(S, K);
 
// This code is contributed by SoumikMondal
</script>
Output: 
aaa

 

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :