#2014
Longest Subsequence Repeated k Times
HardHash TableTwo PointersStringBacktrackingCountingEnumeration
Approaches
💡
Intuition
Time Space
The brute-force approach involves generating all possible subsequences of the string and checking each one to see if it can be repeated k times. This is simple but inefficient due to the exponential number of subsequences.
⚙️
Algorithm
3 steps- 1Step 1: Generate all possible subsequences of the string s.
- 2Step 2: For each subsequence, check if it can be repeated k times in s.
- 3Step 3: Keep track of the longest valid subsequence found, and if there are ties, choose the lexicographically largest one.
solution.py25 lines
1from itertools import combinations
2
3def longest_repeated_subsequence(s, k):
4 n = len(s)
5 longest = ""
6 for length in range(1, n // k + 1):
7 for subseq in combinations(s, length):
8 candidate = ''.join(subseq)
9 if can_form_k_times(candidate, s, k):
10 if (len(candidate) > len(longest)) or (len(candidate) == len(longest) and candidate > longest):
11 longest = candidate
12 return longest
13
14def can_form_k_times(seq, s, k):
15 count = 0
16 j = 0
17 for char in seq:
18 for i in range(j, len(s)):
19 if s[i] == char:
20 count += 1
21 j = i + 1
22 break
23 if count == k * len(seq):
24 return True
25 return FalseSolutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.