Approach
Breadth-first search
For Longest Subsequence Repeated k Times, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 47 lines of C++ from the credited upstream file 2014.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string longestSubsequenceRepeatedK(string s, int k) {4 string ans;5 vector<int> count(26);6 vector<char> possibleChars;7 8 queue<string> q{{""}};9 10 for (const char c : s)11 ++count[c - 'a'];12 13 for (char c = 'a'; c <= 'z'; ++c)14 if (count[c - 'a'] >= k)15 possibleChars.push_back(c);16 17 while (!q.empty()) {18 const string currSubseq = q.front();19 q.pop();20 if (currSubseq.length() * k > s.length())21 return ans;22 for (const char c : possibleChars) {23 const string& newSubseq = currSubseq + c;24 if (isSubsequence(newSubseq, s, k)) {25 q.push(newSubseq);26 ans = newSubseq;27 }28 }29 }30 31 return ans;32 }33 34 private:35 bool isSubsequence(const string& subseq, string& s, int k) {36 int i = 0; 37 for (const char c : s)38 if (c == subseq[i])39 if (++i == subseq.length()) {40 if (--k == 0)41 return true;42 i = 0;43 }44 return false;45 }46};47