File tree 1 file changed +52
-0
lines changed
solution/2000-2099/2014.Longest Subsequence Repeated k Times
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ from collections import Counter , deque
2
+
3
+ class Solution :
4
+ def longestSubsequenceRepeatedK (self , s : str , k : int ) -> str :
5
+ # Step 1: Frequency counter for each character in the string
6
+ freq = Counter (s )
7
+
8
+ # Step 2: Collect all characters with at least k frequency
9
+ candidates = [ch for ch , count in freq .items () if count >= k ]
10
+
11
+ # Step 3: Helper function to check if a given sequence can be repeated k times
12
+ def canBeRepeatedKTimes (subseq ):
13
+ i = 0
14
+ count = 0
15
+ for ch in s :
16
+ if ch == subseq [i ]:
17
+ i += 1
18
+ if i == len (subseq ):
19
+ i = 0
20
+ count += 1
21
+ if count == k :
22
+ return True
23
+ return False
24
+
25
+ # Step 4: Breadth-First Search (BFS) to generate subsequences
26
+ queue = deque (["" ]) # Start with an empty sequence
27
+ longest = ""
28
+
29
+ while queue :
30
+ curr = queue .popleft ()
31
+
32
+ # Try appending each candidate character to the current subsequence
33
+ for ch in candidates :
34
+ new_subseq = curr + ch
35
+
36
+ # Check if the new subsequence is repeatable k times
37
+ if canBeRepeatedKTimes (new_subseq ):
38
+ queue .append (new_subseq )
39
+
40
+ # Update longest if new_subseq is longer or lexicographically larger
41
+ if len (new_subseq ) > len (longest ) or (len (new_subseq ) == len (longest ) and new_subseq > longest ):
42
+ longest = new_subseq
43
+
44
+ return longest
45
+
46
+
47
+ # Example usage:
48
+ sol = Solution ()
49
+ print (sol .longestSubsequenceRepeatedK ("letsleetcode" , 2 )) # Output: "let"
50
+ print (sol .longestSubsequenceRepeatedK ("bb" , 2 )) # Output: "b"
51
+ print (sol .longestSubsequenceRepeatedK ("ab" , 2 )) # Output: ""
52
+ print (sol .longestSubsequenceRepeatedK ("bbabbabbbbabaababab" , 3 )) # Output: "bbbb"
You can’t perform that action at this time.
0 commit comments