Lexicographically smallest K-length subsequence from a given string
Last Updated :
06 May, 2025
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] Generating all Subsequences - O(2^n) time and O(C(n,k)*k+n) space
The idea is to generate all possible subsequences of length k from the input string s, store them in an array, sort them lexicographically, and return the first (smallest) string.
C++
// C++ program to find Lexicographically smallest
// K-length subsequence from a given string
#include <bits/stdc++.h>
using namespace std;
// Recursive function to generate all subsequences of length k
void generateSub(string s, int i, int k, string curr,
vector<string>& result) {
int n = s.length();
// If we've reached end of string and string
// is of length k.
if (i == n) {
if (curr.length() == k) result.push_back(curr);
return;
}
// Include curr character
generateSub(s, i + 1, k, curr + s[i], result);
// Exclude curr character
generateSub(s, i + 1, k, curr, result);
}
string lexSmallest(string s, int k) {
int n = s.length();
vector<string> subsequences;
generateSub(s, 0, k, "", subsequences);
// Sort all subsequences lexicographically
sort(subsequences.begin(), subsequences.end());
// Return the lexicographically smallest subsequence
return subsequences[0];
}
int main() {
string s = "bbcaab";
int k = 3;
cout << lexSmallest(s, k);
return 0;
}
Java
// Java program to find Lexicographically smallest
// K-length subsequence from a given string
import java.util.*;
class GfG {
// Recursive function to generate all subsequences of length k
static void generateSub(String s, int i, int k,
String curr, ArrayList<String> result) {
int n = s.length();
// If we've reached end of string and string
// is of length k.
if (i == n) {
if (curr.length() == k) result.add(curr);
return;
}
// Include curr character
generateSub(s, i + 1, k, curr + s.charAt(i), result);
// Exclude curr character
generateSub(s, i + 1, k, curr, result);
}
static String lexSmallest(String s, int k) {
int n = s.length();
ArrayList<String> subsequences = new ArrayList<>();
generateSub(s, 0, k, "", subsequences);
// Sort all subsequences lexicographically
Collections.sort(subsequences);
// Return the lexicographically smallest subsequence
return subsequences.get(0);
}
public static void main(String[] args) {
String s = "bbcaab";
int k = 3;
System.out.println(lexSmallest(s, k));
}
}
Python
# Python program to find Lexicographically smallest
# K-length subsequence from a given string
# Recursive function to generate all subsequences of length k
def generateSub(s, i, k, curr, result):
n = len(s)
# If we've reached end of string and string
# is of length k.
if i == n:
if len(curr) == k:
result.append(curr)
return
# Include curr character
generateSub(s, i + 1, k, curr + s[i], result)
# Exclude curr character
generateSub(s, i + 1, k, curr, result)
def lexSmallest(s, k):
n = len(s)
subsequences = []
generateSub(s, 0, k, "", subsequences)
# Sort all subsequences lexicographically
subsequences.sort()
# Return the lexicographically smallest subsequence
return subsequences[0]
if __name__ == "__main__":
s = "bbcaab"
k = 3
print(lexSmallest(s, k))
C#
// C# program to find Lexicographically smallest
// K-length subsequence from a given string
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to generate all subsequences of length k
static void generateSub(string s, int i, int k,
string curr, List<string> result) {
int n = s.Length;
// If we've reached end of string and string
// is of length k.
if (i == n) {
if (curr.Length == k) result.Add(curr);
return;
}
// Include curr character
generateSub(s, i + 1, k, curr + s[i], result);
// Exclude curr character
generateSub(s, i + 1, k, curr, result);
}
static string lexSmallest(string s, int k) {
int n = s.Length;
List<string> subsequences = new List<string>();
generateSub(s, 0, k, "", subsequences);
// Sort all subsequences lexicographically
subsequences.Sort();
// Return the lexicographically smallest subsequence
return subsequences[0];
}
static void Main(string[] args) {
string s = "bbcaab";
int k = 3;
Console.WriteLine(lexSmallest(s, k));
}
}
JavaScript
// JavaScript program to find Lexicographically smallest
// K-length subsequence from a given string
// Recursive function to generate all subsequences of length k
function generateSub(s, i, k, curr, result) {
let n = s.length;
// If we've reached end of string and string
// is of length k.
if (i === n) {
if (curr.length === k) result.push(curr);
return;
}
// Include curr character
generateSub(s, i + 1, k, curr + s[i], result);
// Exclude curr character
generateSub(s, i + 1, k, curr, result);
}
function lexSmallest(s, k) {
let n = s.length;
let subsequences = [];
generateSub(s, 0, k, "", subsequences);
// Sort all subsequences lexicographically
subsequences.sort();
// Return the lexicographically smallest subsequence
return subsequences[0];
}
let s = "bbcaab";
let k = 3;
console.log(lexSmallest(s, k));
Time Complexity: O(2^n), at each index we have two choices: include the character or exclude it.
Auxiliary Space: O(C(n,k)*k + n), where C(n,k) equals the number of subsequences of length k, which can be created from a string of length n.
[Expected Approach] Using Stack - O(n) time and O(n) space
We use a stack that maintain the result so far. We process each character of the string from left to right, always maintaining the lexicographically smallest subsequence of the appropriate length seen so far. Whenever we encounter a smaller character than top of the stack, we remove larger characters to ensure the smallest possible subsequence, also ensuring we'll still have enough remaining characters to form a subsequence of length k.
Step by step approach:
- Process each character from left to right, maintaining a stack of the best possible subsequence.
- Pop characters from the stack when a smaller one is found and we have enough remaining characters.
- Add the current character to the stack only if we haven't collected k characters yet.
- Build the final result by emptying the stack and reversing the characters.
C++
// C++ program to find Lexicographically smallest
// K-length subsequence from a given string
#include <bits/stdc++.h>
using namespace std;
string lexSmallest(string s, int k) {
int n = s.length();
stack<char> st;
for (int i=0; i<n; i++) {
// While stack is not empty, and top
// of stack is less than current char
// while ensuring there are enough
// characters left to make subsequence
// of length k.
while (!st.empty() && st.top()>s[i] && st.size()-1+n-i >= k) {
st.pop();
}
// If size of stack is less than k.
if (st.size() < k) st.push(s[i]);
}
string res = "";
while (!st.empty()) {
res += st.top();
st.pop();
}
// Reverse the string to get the
// final resultant string
reverse(res.begin(), res.end());
return res;
}
int main() {
string s = "bbcaab";
int k = 3;
cout << lexSmallest(s, k);
return 0;
}
Java
// Java program to find Lexicographically smallest
// K-length subsequence from a given string
import java.util.*;
class GfG {
static String lexSmallest(String s, int k) {
int n = s.length();
Stack<Character> st = new Stack<>();
for (int i = 0; i < n; i++) {
// While stack is not empty, and top
// of stack is less than current char
// while ensuring there are enough
// characters left to make subsequence
// of length k.
while (!st.isEmpty() && st.peek() > s.charAt(i)
&& st.size() - 1 + n - i >= k) {
st.pop();
}
// If size of stack is less than k.
if (st.size() < k) st.push(s.charAt(i));
}
StringBuilder res = new StringBuilder();
while (!st.isEmpty()) {
res.append(st.pop());
}
// Reverse the string to get the
// final resultant string
res.reverse();
return res.toString();
}
public static void main(String[] args) {
String s = "bbcaab";
int k = 3;
System.out.println(lexSmallest(s, k));
}
}
Python
# Python program to find Lexicographically smallest
# K-length subsequence from a given string
def lexSmallest(s, k):
n = len(s)
st = []
for i in range(n):
# While stack is not empty, and top
# of stack is less than current char
# while ensuring there are enough
# characters left to make subsequence
# of length k.
while st and st[-1] > s[i] and len(st) - 1 + n - i >= k:
st.pop()
# If size of stack is less than k.
if len(st) < k:
st.append(s[i])
res = ""
while st:
res += st.pop()
# Reverse the string to get the
# final resultant string
res = res[::-1]
return res
if __name__ == "__main__":
s = "bbcaab"
k = 3
print(lexSmallest(s, k))
C#
// C# program to find Lexicographically smallest
// K-length subsequence from a given string
using System;
using System.Collections.Generic;
using System.Text;
class GfG {
static string lexSmallest(string s, int k) {
int n = s.Length;
Stack<char> st = new Stack<char>();
for (int i = 0; i < n; i++) {
// While stack is not empty, and top
// of stack is less than current char
// while ensuring there are enough
// characters left to make subsequence
// of length k.
while (st.Count > 0 && st.Peek() > s[i] &&
st.Count - 1 + n - i >= k) {
st.Pop();
}
// If size of stack is less than k.
if (st.Count < k) st.Push(s[i]);
}
StringBuilder res = new StringBuilder();
while (st.Count > 0) {
res.Append(st.Pop());
}
// Reverse the string to get the
// final resultant string
char[] arr = res.ToString().ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
static void Main(string[] args) {
string s = "bbcaab";
int k = 3;
Console.WriteLine(lexSmallest(s, k));
}
}
JavaScript
// JavaScript program to find Lexicographically smallest
// K-length subsequence from a given string
function lexSmallest(s, k) {
let n = s.length;
let st = [];
for (let i = 0; i < n; i++) {
// While stack is not empty, and top
// of stack is less than current char
// while ensuring there are enough
// characters left to make subsequence
// of length k.
while (st.length > 0 && st[st.length - 1] > s[i]
&& st.length - 1 + n - i >= k) {
st.pop();
}
// If size of stack is less than k.
if (st.length < k) st.push(s[i]);
}
let res = "";
while (st.length > 0) {
res += st.pop();
}
// Reverse the string to get the
// final resultant string
res = res.split("").reverse().join("");
return res;
}
let s = "bbcaab";
let k = 3;
console.log(lexSmallest(s, k));
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read