Longest Subsequence Repeated k Times - Problem
Find the Longest Subsequence Repeated k Times
You are given a string
A subsequence is formed by deleting some (or no) characters from a string without changing the order of remaining characters. A subsequence
Example: In string
Goal: Return the longest such subsequence. If multiple exist with same length, return the lexicographically largest one.
You are given a string
s of length n and an integer k. Your task is to find the longest subsequence that appears k times in the string.A subsequence is formed by deleting some (or no) characters from a string without changing the order of remaining characters. A subsequence
seq is considered repeated k times if we can find seq * k (seq concatenated k times) as a subsequence of the original string.Example: In string
"bababcba", the subsequence "bba" is repeated 2 times because "bbabba" (bba concatenated twice) can be found as a subsequence by selecting characters at positions that maintain order.Goal: Return the longest such subsequence. If multiple exist with same length, return the lexicographically largest one.
Input & Output
example_1.py โ Basic Example
$
Input:
s = "letsleetcode", k = 2
โบ
Output:
"eet"
๐ก Note:
"eet" is a subsequence of "letsleetcode". When repeated 2 times, "eeteet" is also a subsequence of the original string. This is the longest such subsequence.
example_2.py โ Single Character
$
Input:
s = "bb", k = 2
โบ
Output:
"b"
๐ก Note:
"b" repeated 2 times gives "bb", which is a subsequence of "bb". This is the only valid subsequence that can be repeated k times.
example_3.py โ No Solution
$
Input:
s = "ab", k = 2
โบ
Output:
""
๐ก Note:
No character appears at least 2 times, so no subsequence can be repeated 2 times. Return empty string.
Visualization
Tap to expand
Understanding the Visualization
1
Evidence Collection
Count how many times each letter appears - eliminate letters that don't appear enough times
2
Pattern Building
Try building patterns starting with the 'best' letters first (Z, Y, X... down to A)
3
Verification
For each potential pattern, check if it can be found k times in the original message
Key Takeaway
๐ฏ Key Insight: By filtering out characters that appear less than k times and using backtracking with lexicographic ordering, we can efficiently find the optimal solution without checking every possible subsequence!
Time & Space Complexity
Time Complexity
O(k * n * 2^c)
Where c is number of characters appearing at least k times. Each subsequence takes O(k*n) to verify.
โ Linear Growth
Space Complexity
O(n)
Space for recursion stack and character frequency counting
โก Linearithmic Space
Constraints
- n == s.length
- 2 โค k โค 2000
- 2 โค n โค 2000
- s consists of lowercase English letters
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code