Open In App

Lexicographically largest subsequence such that every character occurs at least k times

Last Updated : 20 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given a string s and an integer k, the task is to find lexicographically largest subsequence of S, say T, such that every character in T must occur at least k times.

Examples: 

Input : s = "banana", k = 2.
Output : "nn"
Explanation:
Possible subsequence where each character exists at least 2 times are:

Check if a line touches or intersects a circle

From the above subsequences, "nn" is the lexicographically largest.

Input: s = "zzyyxx", k = 2
Output: "zzyyxx"

Input: s = "xxyyzz", k = 2
Output: "zz"

Approach:

The idea is to use a greedy approach by iterating from the highest character ('z') to the lowest ('a'). For each character, we count its occurrences starting from the last valid position and include it in the result if it appears at least k times. This ensures that higher characters are prioritized, maintaining the lexicographical order, and the frequency constraint is satisfied by only considering valid segments of the string.

Step by step approach:

  1. Iterate from 'z' to 'a' to prioritize higher characters for the lexicographical order.
  2. For each character, count its occurrences starting from the last valid position in the string.
  3. If the character appears at least k times, append all its occurrences to the result. Update the starting position to the index immediately after the last occurrence of the current character to avoid overlaps.
  4. Repeat the process until all characters are processed, ensuring the result is the largest valid subsequence.
C++
// C++ program to find Lexicographically 
// largestsubsequence such that every 
// character occurs at least k times
#include <bits/stdc++.h>
using namespace std;
 
string largestSubsequence(string &s, int k) {
    int n = s.length();
    
    string res = "";
    int last = 0;
    
    for (char ch='z'; ch>='a'; ch--) {
        int cnt = 0;
        int index = -1;
        
        // Count frequency of char ch 
        // after the last index.
        for (int i=last; i<n; i++) {
            if (s[i] == ch) {
                cnt++;
                
                // Store the index of last 
                // occurrence 
                index = i;
            }
        }
        
        // If frequency is greater than 
        // equal to k.
        if (cnt >= k) {
            
            // Append the current char 
            // cnt times
            for (int i=0; i<cnt; i++) {
                res.push_back(ch);
            }
            
            // Update the last index 
            last = index + 1;
        }
    }
    
    return res;
}
 
int main() {
    string s = "banana";
    int k = 2;
    string res = largestSubsequence(s, k);
    cout << res;
    return 0;
}
Java
// Java program to find Lexicographically 
// largest subsequence such that every 
// character occurs at least k times

import java.util.*;

class GfG {

    // function to find lexicographically largest subsequence
    // such that every character occurs at least k times
    static String largestSubsequence(String s, int k) {
        int n = s.length();
        
        String res = "";
        int last = 0;
        
        for (char ch = 'z'; ch >= 'a'; ch--) {
            int cnt = 0;
            int index = -1;
            
            // Count frequency of char ch 
            // after the last index.
            for (int i = last; i < n; i++) {
                if (s.charAt(i) == ch) {
                    cnt++;
                    
                    // Store the index of last 
                    // occurrence 
                    index = i;
                }
            }
            
            // If frequency is greater than 
            // equal to k.
            if (cnt >= k) {
                
                // Append the current char 
                // cnt times
                for (int i = 0; i < cnt; i++) {
                    res += ch;
                }
                
                // Update the last index 
                last = index + 1;
            }
        }
        
        return res;
    }

    public static void main(String[] args) {
        String s = "banana";
        int k = 2;
        String res = largestSubsequence(s, k);
        System.out.println(res);
    }
}
Python
# Python program to find Lexicographically 
# largest subsequence such that every 
# character occurs at least k times

# function to find lexicographically largest subsequence
# such that every character occurs at least k times
def largestSubsequence(s, k):
    n = len(s)
    
    res = ""
    last = 0
    
    for ch in range(ord('z'), ord('a') - 1, -1):
        cnt = 0
        index = -1
        
        # Count frequency of char ch 
        # after the last index.
        for i in range(last, n):
            if s[i] == chr(ch):
                cnt += 1
                
                # Store the index of last 
                # occurrence 
                index = i
        
        # If frequency is greater than 
        # equal to k.
        if cnt >= k:
            
            # Append the current char 
            # cnt times
            res += chr(ch) * cnt
            
            # Update the last index 
            last = index + 1
    
    return res

if __name__ == "__main__":
    s = "banana"
    k = 2
    res = largestSubsequence(s, k)
    print(res)
C#
// C# program to find Lexicographically 
// largest subsequence such that every 
// character occurs at least k times

using System;

class GfG {

    // function to find lexicographically largest subsequence
    // such that every character occurs at least k times
    static string largestSubsequence(string s, int k) {
        int n = s.Length;
        
        string res = "";
        int last = 0;
        
        for (char ch = 'z'; ch >= 'a'; ch--) {
            int cnt = 0;
            int index = -1;
            
            // Count frequency of char ch 
            // after the last index.
            for (int i = last; i < n; i++) {
                if (s[i] == ch) {
                    cnt++;
                    
                    // Store the index of last 
                    // occurrence 
                    index = i;
                }
            }
            
            // If frequency is greater than 
            // equal to k.
            if (cnt >= k) {
                
                // Append the current char 
                // cnt times
                for (int i = 0; i < cnt; i++) {
                    res += ch;
                }
                
                // Update the last index 
                last = index + 1;
            }
        }
        
        return res;
    }

    static void Main() {
        string s = "banana";
        int k = 2;
        string res = largestSubsequence(s, k);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to find Lexicographically 
// largest subsequence such that every 
// character occurs at least k times

// function to find lexicographically largest subsequence
// such that every character occurs at least k times
function largestSubsequence(s, k) {
    let n = s.length;
    
    let res = "";
    let last = 0;
    
    for (let ch = 'z'.charCodeAt(0); ch >= 'a'.charCodeAt(0); ch--) {
        let cnt = 0;
        let index = -1;
        
        // Count frequency of char ch 
        // after the last index.
        for (let i = last; i < n; i++) {
            if (s[i] === String.fromCharCode(ch)) {
                cnt++;
                
                // Store the index of last 
                // occurrence 
                index = i;
            }
        }
        
        // If frequency is greater than 
        // equal to k.
        if (cnt >= k) {
            
            // Append the current char 
            // cnt times
            res += String.fromCharCode(ch).repeat(cnt);
            
            // Update the last index 
            last = index + 1;
        }
    }
    
    return res;
}

let s = "banana";
let k = 2;
let res = largestSubsequence(s, k);
console.log(res);

Output
nn

Time Complexity: O(n), as string is traversed once, and characters are appended to result at most n times.
Auxiliary Space: O(n)


Practice Tags :

Similar Reads