VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lexicographically-largest-subsequence-every-character-occurs-least-k-times/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 20 Mar, 2025

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.

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)

Comment