Lexicographically largest sub-sequence of the given string
Last Updated :
11 Oct, 2024
Given string str containing lowercase characters, the task is to find the lexicographically largest sub-sequence of str.
Examples:
Input: str = "abc"
Output: c
All possible sub-sequences are "a", "ab", "ac", "b", "bc" and "c"
and "c" is the largest among them (lexicographically)
Input: str = "geeksforgeeks"
Output: ss
Approach:
Let mx be the lexicographically largest character in the string. Since we want the lexicographically largest sub-sequence we should include all occurrences of mx. Now after all the occurrences have been used, the same process can be repeated for the remaining string (i.e. sub-string after the last occurrence of mx) and so on until the there are no more characters left.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the lexicographically
// largest sub-sequence of s
string getSubSeq(string s, int n)
{
string res = "";
int cr = 0;
while (cr < n) {
// Get the max character from the string
char mx = s[cr];
for (int i = cr + 1; i < n; i++)
mx = max(mx, s[i]);
int lst = cr;
// Use all the occurrences of the
// current maximum character
for (int i = cr; i < n; i++)
if (s[i] == mx) {
res.push_back(s[i]);
lst = i;
}
// Repeat the steps for the remaining string
cr = lst + 1;
}
return res;
}
// Driver code
int main()
{
string s = "geeksforgeeks";
int n = s.length();
cout << getSubSeq(s, n);
}
Java
// Java implementation of the approach
class GFG {
// Function to return the lexicographically
// largest sub-sequence of s
static String getSubSeq(String s, int n) {
StringBuilder res = new StringBuilder();
int cr = 0;
while (cr < n) {
// Get the max character from the String
char mx = s.charAt(cr);
for (int i = cr + 1; i < n; i++)
{
mx = (char) Math.max(mx, s.charAt(i));
}
int lst = cr;
// Use all the occurrences of the
// current maximum character
for (int i = cr; i < n; i++) {
if (s.charAt(i) == mx) {
res.append(s.charAt(i));
lst = i;
}
}
// Repeat the steps for
// the remaining String
cr = lst + 1;
}
return res.toString();
}
public static void main(String[] args) {
String s = "geeksforgeeks";
int n = s.length();
System.out.println(getSubSeq(s, n));
}
}
// This code is contributed by Rajput-Ji
Python
# Python 3 implementation of the approach
# Function to return the lexicographically
# largest sub-sequence of s
def getSubSeq(s, n):
# character list to store result
res = []
cr = 0
while (cr < n):
# Get the max character from
# the string
mx = s[cr]
for i in range(cr + 1, n):
mx = max(mx, s[i])
lst = cr
# Use all the occurrences of the
# current maximum character
for i in range(cr,n):
if (s[i] == mx):
res.append(s[i])
lst = i
# Repeat the steps for the
# remaining string
cr = lst + 1
return ''.join(res)
# Driver code
if __name__ == '__main__':
s = "geeksforgeeks"
n = len(s)
print(getSubSeq(s, n))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System;
using System.Text;
class GFG {
// Function to return the lexicographically
// largest sub-sequence of s
static String getSubSeq(String s, int n) {
StringBuilder res = new StringBuilder();
int cr = 0;
while (cr < n) {
// Get the max character from
// the String
char mx = s[cr];
for (int i = cr + 1; i < n; i++) {
mx = (char) Math.Max(mx, s[i]);
}
int lst = cr;
// Use all the occurrences of the
// current maximum character
for (int i = cr; i < n; i++) {
if (s[i] == mx) {
res.Append(s[i]);
lst = i;
}
}
// Repeat the steps for
// the remaining String
cr = lst + 1;
}
return res.ToString();
}
// Driver code
public static void Main(String[] args)
{
String s = "geeksforgeeks";
int n = s.Length;
Console.WriteLine(getSubSeq(s, n));
}
}
// This code is contributed by 29AjayKumar
JavaScript
// Javascript implementation of the approach
// Function to return the lexicographically
// largest sub-sequence of s
function getSubSeq(s, n)
{
var res = [];
var cr = 0;
while (cr < n) {
// Get the max character from the string
var mx = s[cr].charCodeAt(0);
for (var i = cr + 1; i < n; i++)
mx = Math.max(mx, s[i].charCodeAt(0));
var lst = cr;
// Use all the occurrences of the
// current maximum character
for (var i = cr; i < n; i++)
if (s[i].charCodeAt(0) == mx) {
res.push(s[i]);
lst = i;
}
// Repeat the steps for the remaining string
cr = lst + 1;
}
return res.join('');
}
// Driver code
var s = "geeksforgeeks";
var n = s.length;
console.log( getSubSeq(s, n));
// This code is contributed by famously.
Complexity Analysis:
- Time Complexity: O(N) where N is the length of the string.
- Auxiliary Space: O(N)
New Approach:- Another approach to solve this problem is using a stack. The idea is to traverse the given string from left to right and push the characters onto the stack. If the current character is greater than the top of the stack, we pop the elements from the stack until we encounter a character that is greater than the current character or the stack becomes empty. Then, we push the current character onto the stack. After traversing the entire string, the stack will contain the lexicographically largest sub-sequence.
Below is the implementation of the above approach:-
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the lexicographically
// largest sub-sequence of s
string getSubSeq(string s, int n)
{
stack<char> st;
for (int i = 0; i < n; i++) {
while (!st.empty() && s[i] > st.top())
st.pop();
st.push(s[i]);
}
string res = "";
while (!st.empty()) {
res += st.top();
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
// Driver code
int main()
{
string s = "geeksforgeeks";
int n = s.length();
cout << getSubSeq(s, n);
}
Java
import java.util.*;
public class Main {
public static String getSubSeq(String s, int n) {
Stack<Character> st = new Stack<>();
for (int i = 0; i < n; i++) {
while (!st.empty() && s.charAt(i) > st.peek())
st.pop();
st.push(s.charAt(i));
}
StringBuilder res = new StringBuilder();
while (!st.empty()) {
res.append(st.peek());
st.pop();
}
return res.reverse().toString();
}
public static void main(String[] args) {
String s = "geeksforgeeks";
int n = s.length();
System.out.println(getSubSeq(s, n));
}
}
Python
# Python implementation of the approach
# Function to return the lexicographically
# largest sub-sequence of s
def getSubSeq(s):
stack = []
for char in s:
while stack and char > stack[-1]:
stack.pop()
stack.append(char)
# Convert the stack to a string in reverse order
res = ''.join(stack[::-1])
return res
# Driver code
if __name__ == "__main__":
s = "geeksforgeeks"
result = getSubSeq(s)
print(result)
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static string GetSubSeq(string s, int n)
{
Stack<char> st = new Stack<char>();
for (int i = 0; i < n; i++)
{
while (st.Any() && s[i] > st.Peek())
{
st.Pop();
}
st.Push(s[i]);
}
string res = "";
while (st.Any())
{
res += st.Peek();
st.Pop();
}
return new string(res.Reverse().ToArray());
}
public static void Main()
{
string s = "geeksforgeeks";
int n = s.Length;
Console.WriteLine(GetSubSeq(s, n));
}
}
JavaScript
function getSubSeq(s, n) {
let st = [];
for (let i = 0; i < n; i++) {
while (st.length > 0 && s[i] > st[st.length - 1])
st.pop();
st.push(s[i]);
}
let res = "";
while (st.length > 0) {
res += st[st.length - 1];
st.pop();
}
return res.split("").reverse().join("");
}
// Driver code
let s = "geeksforgeeks";
let n = s.length;
console.log(getSubSeq(s, n));
"Note that the time complexity of this approach is O(n) and space complexity is also O(n) due to the use of stack."
Time complexity:- The time complexity of the given approach is O(n) as we are iterating over each character of the given string once.
Space complexity:-The space complexity of the given approach is also O(n) as we are using a stack to store the characters of the sub-sequence. In the worst-case scenario, where all the characters of the string are in decreasing order, the stack will contain all the characters of the string.
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
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
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
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
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read