Longest Subsequence Repeated k Times - Problem

You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.

A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.

A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.

For example, "bba" is repeated 2 times in the string "bababcba", because the string "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the string "bababcba".

Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.

Input & Output

Example 1 — Basic Case
$ Input: s = "letsleetcode", k = 2
Output: "let"
💡 Note: The subsequence "let" can be repeated 2 times to form "letlet", which is a subsequence of "letsleetcode". This is the longest such subsequence.
Example 2 — No Valid Subsequence
$ Input: s = "bb", k = 3
Output: ""
💡 Note: No character appears 3 or more times, so no subsequence can be repeated 3 times.
Example 3 — Single Character
$ Input: s = "ab", k = 1
Output: "b"
💡 Note: When k=1, we want the lexicographically largest subsequence, which is "b".

Constraints

  • 2 ≤ s.length ≤ 2000
  • 2 ≤ k ≤ 2000
  • s consists of lowercase English letters

Visualization

Tap to expand
Longest Subsequence Repeated k Times INPUT String s: l e t s l e e t c o d e s = "letsleetcode" k = 2 Character Counts: l:2 e:4 t:2 s:1 c:1 o:1 d:1 Chars with count >= k: l, e, t ALGORITHM STEPS 1 Count Characters Keep chars with freq >= k 2 Generate Candidates BFS: longer sequences first 3 Check Validity Is seq*k subsequence of s? 4 Return Best Longest + lex largest Verification: "let" * 2 Target: "letlet" s: letsleetcode ^ ^^ ^^ l et le t OK - Valid subsequence! FINAL RESULT Output: "let" Why "let"? Length 3 (longest possible) "letlet" is subsequence of "letsleetcode" Lex largest at length 3 Candidates at len 3: tte, ttl, tet, tel, tlt... ...let, lee, elt, ele... "let" OK Key Insight: The answer length is at most n/k. Use BFS starting from longest candidates, checking lexicographically largest first. Only characters with frequency >= k can appear in the answer. Time: O(n * 26^(n/k)) TutorialsPoint - Longest Subsequence Repeated k Times | Optimal Solution (BFS + Greedy)
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
12.5K Views
Medium Frequency
~35 min Avg. Time
487 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen