Longest Subsequence Repeated k Times LeetCode solution in Python
1class Solution:2def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:3n = len(s)4max_chunk_sz = n // k56d = collections.Counter(s)7chars = sorted([c for c in d if d[c] >= k], reverse=True)8if not chars:9return ""1011old_cand = chars12for m in range(2, max_chunk_sz + 1):13new_cand = []14for t in self.get_next_level(old_cand, chars):15if self.find(s, t * k):16new_cand.append(t)1718if len(new_cand) == 0:19break20old_cand = new_cand21return old_cand[0]2223def get_next_level(self, cand, chars):24for s in cand:25for ch in chars:26yield s + ch2728def find(self, s, t):29# find subsequence t in s30j = 031for i in range(len(s)):32if s[i] == t[j]:33j += 134if j == len(t):35return True36return False