You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeatedk times in string s.
A subsequence is a string that can be derived from anotwher string by deleting some or no characters without changing the order of the remaining characters.
A subsequence seq is repeatedk times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seqk times.
For example, "bba" is repeated 2 times in the string "bababcba", because the string "bbabba", constructed by concatenating "bba"2 times, is a subsequence of the string "**b**a**bab**c**ba**".
Return the longest subsequence repeatedktimes in strings. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
Input: s ="letsleetcode", k =2Output: "let"Explanation: There are two longest subsequences repeated 2 times:"let" and "ete"."let"is the lexicographically largest one.
To solve this problem, we need to find the longest subsequence that, when repeated k times, remains a subsequence of the original string s, and among all such subsequences, select the lexicographically largest one. Since only characters that appear at least k times in s can contribute to such a subsequence, we can filter out less frequent characters immediately.
Count the frequency of each character in s and retain only those that appear at least k times.
The maximum possible length of a valid subsequence is limited by the constraint n < 8k, so the answer’s length cannot exceed 7.
Generate all possible combinations and permutations of the filtered characters up to the maximum allowed length.
Use a queue (BFS) to build candidate subsequences, always extending the current string by appending valid characters in reverse lexicographical order to prioritize larger answers.
For each candidate, check if its k-fold concatenation is a subsequence of s. The first valid candidate found with the maximum length and lexicographical order is the answer.
⏰ Time complexity: O(n ⋅ m!), where n is the length of the string and m is the maximum possible length of the answer (bounded by the number of characters in s that appear at least k times). For each candidate subsequence (at most m!), checking if it is repeated k times as a subsequence takes O(n) time.
🧺 Space complexity: O(m!), since the queue and candidate set can hold up to m! subsequences at any time.