πΉ Problem: 2014. Longest Subsequence Repeated k Times
Difficulty: #Hard
Tags: #String, #Greedy, #BFS, #Hashing
π Problem Summary
We are given a string
s
and an integerk
. Our task is to find the longest subsequence (not substring) such that when this subsequence is repeatedk
times (i.e.,sub * k
), the resulting string is still a subsequence ofs
.If multiple valid solutions exist, return the lexicographically largest one. If no such subsequence exists, return an empty string.
π§ My Thought Process
-
Brute Force Idea:
- There was no waaaay, I could have come up with a brute force solution for this problem. The constraints are too large, and generating all subsequences would be infeasible.
-
Optimized Strategy:
- Any valid character in the final answer must appear at least
k
times ins
. - Generate candidate subsequences using only these frequent characters.
- Use BFS to build subsequences of increasing length.
- For each candidate
sub
, check ifsub * k
is a subsequence ofs
using a greedy check via iterator traversal (all(ch in iter(s) for ch in sub * k)
). - Use reverse lexicographical BFS order to ensure lexicographically largest answer is found first.
- Any valid character in the final answer must appear at least
-
Algorithm Used:
- [[BFS]]
- [[greedy]]
- [[counter]]
βοΈ Code Implementation (Python)
from collections import Counter, deque
class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
ans = ""
candidate = sorted(
[c for c, w in Counter(s).items() if w >= k], reverse=True
)
q = deque(candidate)
while q:
curr = q.popleft()
if len(curr) > len(ans):
ans = curr
for ch in candidate:
nxt = curr + ch
it = iter(s)
if all(c in it for c in nxt * k):
q.append(nxt)
return ans
β±οΈ Time & Space Complexity
- Time: Worst-case exponential in terms of candidate growth, but pruned effectively using frequency filtering and subsequence validation.
- Space: O(N) β mainly for queue and frequency dictionary.
π§© Key Takeaways
- β Learned how greedy + BFS can solve what feels like a DP string problem.
- π‘ The trick of checking
sub * k
as a subsequence usingiter()
is powerful. - π Problems involving βrepeated k timesβ often benefit from thinking in multiples and frequency-based pruning.
π Reflection (Self-Check)
- [ ] Could I solve this without help? β β Not fully. I understood the statement and explored ideas, but couldn't implement the working solution.
- [ ] Did I write code from scratch? β β No, I referred to the editorial solution.
- [x] Did I understand why it works? β β Yes, after explanation.
- [x] Will I be able to recall this in a week? β β Yes, due to clear BFS structure and pruning trick.
π Related Problems
- [[395 Longest Substring with At Least K Repeating Characters]]
π Progress Tracker
Metric | Value |
---|---|
Day | 32 |
Total Problems Solved | 365 |
Confidence Today | π |
Top comments (0)