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
- 44 lines of Java from the credited upstream file 2014.java.
- 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 String longestSubsequenceRepeatedK(String s, int k) {3 String ans = "";4 int[] count = new int[26];5 List<Character> possibleChars = new ArrayList<>();6 7 Queue<String> q = new ArrayDeque<>(List.of(""));8 9 for (final char c : s.toCharArray())10 ++count[c - 'a'];11 12 for (char c = 'a'; c <= 'z'; ++c)13 if (count[c - 'a'] >= k)14 possibleChars.add(c);15 16 while (!q.isEmpty()) {17 final String currSubseq = q.poll();18 if (currSubseq.length() * k > s.length())19 return ans;20 for (final char c : possibleChars) {21 final String newSubseq = currSubseq + c;22 if (isSubsequence(newSubseq, s, k)) {23 q.offer(newSubseq);24 ans = newSubseq;25 }26 }27 }28 29 return ans;30 }31 32 private boolean isSubsequence(final String subseq, final String s, int k) {33 int i = 0; 34 for (final char c : s.toCharArray())35 if (c == subseq.charAt(i))36 if (++i == subseq.length()) {37 if (--k == 0)38 return true;39 i = 0;40 }41 return false;42 }43}44