![]() |
VOOZH | about |
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
ktimes. 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:
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.nn
Time Complexity: O(n), as string is traversed once, and characters are appended to result at most n times.
Auxiliary Space: O(n)