Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
"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.
Example 1:
Input: s = "letsleetcode", k = 2 Output: "let" Explanation: There are two longest subsequences repeated 2 times: "let" and "ete". "let" is the lexicographically largest one.
Example 2:
Input: s = "bb", k = 2 Output: "b" Explanation: The longest subsequence repeated 2 times is "b".
Example 3:
Input: s = "ab", k = 2 Output: "" Explanation: There is no subsequence repeated 2 times. Empty string is returned.
Constraints:
n == s.length2 <= k <= 20002 <= n < min(2001, k * 8)s consists of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Two Pointers · Backtracking
"letsleetcode" 2
"bb" 2
"ab" 2
longest-substring-with-at-least-k-repeating-characters)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2014: Longest Subsequence Repeated k Times
class Solution {
private char[] s;
public String longestSubsequenceRepeatedK(String s, int k) {
this.s = s.toCharArray();
int[] cnt = new int[26];
for (char c : this.s) {
cnt[c - 'a']++;
}
List<Character> cs = new ArrayList<>();
for (char c = 'a'; c <= 'z'; ++c) {
if (cnt[c - 'a'] >= k) {
cs.add(c);
}
}
Deque<String> q = new ArrayDeque<>();
q.offer("");
String ans = "";
while (!q.isEmpty()) {
String cur = q.poll();
for (char c : cs) {
String nxt = cur + c;
if (check(nxt, k)) {
ans = nxt;
q.offer(nxt);
}
}
}
return ans;
}
private boolean check(String t, int k) {
int i = 0;
for (char c : s) {
if (c == t.charAt(i)) {
i++;
if (i == t.length()) {
if (--k == 0) {
return true;
}
i = 0;
}
}
}
return false;
}
}
// Accepted solution for LeetCode #2014: Longest Subsequence Repeated k Times
func longestSubsequenceRepeatedK(s string, k int) string {
check := func(t string, k int) bool {
i := 0
for _, c := range s {
if byte(c) == t[i] {
i++
if i == len(t) {
k--
if k == 0 {
return true
}
i = 0
}
}
}
return false
}
cnt := [26]int{}
for i := 0; i < len(s); i++ {
cnt[s[i]-'a']++
}
cs := []byte{}
for c := byte('a'); c <= 'z'; c++ {
if cnt[c-'a'] >= k {
cs = append(cs, c)
}
}
q := []string{""}
ans := ""
for len(q) > 0 {
cur := q[0]
q = q[1:]
for _, c := range cs {
nxt := cur + string(c)
if check(nxt, k) {
ans = nxt
q = append(q, nxt)
}
}
}
return ans
}
# Accepted solution for LeetCode #2014: Longest Subsequence Repeated k Times
class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
def check(t: str, k: int) -> bool:
i = 0
for c in s:
if c == t[i]:
i += 1
if i == len(t):
k -= 1
if k == 0:
return True
i = 0
return False
cnt = Counter(s)
cs = [c for c in ascii_lowercase if cnt[c] >= k]
q = deque([""])
ans = ""
while q:
cur = q.popleft()
for c in cs:
nxt = cur + c
if check(nxt, k):
ans = nxt
q.append(nxt)
return ans
// Accepted solution for LeetCode #2014: Longest Subsequence Repeated k Times
/**
* [2014] Longest Subsequence Repeated k Times
*
* 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 "<u>b</u>a<u>bab</u>c<u>ba</u>".
*
* 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.
*
* Example 1:
* <img alt="example 1" src="https://assets.leetcode.com/uploads/2021/08/30/longest-subsequence-repeat-k-times.png" style="width: 457px; height: 99px;" />
* Input: s = "letsleetcode", k = 2
* Output: "let"
* Explanation: There are two longest subsequences repeated 2 times: "let" and "ete".
* "let" is the lexicographically largest one.
*
* Example 2:
*
* Input: s = "bb", k = 2
* Output: "b"
* Explanation: The longest subsequence repeated 2 times is "b".
*
* Example 3:
*
* Input: s = "ab", k = 2
* Output: ""
* Explanation: There is no subsequence repeated 2 times. Empty string is returned.
*
*
* Constraints:
*
* n == s.length
* 2 <= n, k <= 2000
* 2 <= n < k * 8
* s consists of lowercase English letters.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/longest-subsequence-repeated-k-times/
// discuss: https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn longest_subsequence_repeated_k(s: String, k: i32) -> String {
String::new()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2014_example_1() {
let s = "letsleetcode".to_string();
let k = 2;
let result = "let".to_string();
assert_eq!(Solution::longest_subsequence_repeated_k(s, k), result);
}
#[test]
#[ignore]
fn test_2014_example_2() {
let s = "bb".to_string();
let k = 2;
let result = "b".to_string();
assert_eq!(Solution::longest_subsequence_repeated_k(s, k), result);
}
#[test]
#[ignore]
fn test_2014_example_3() {
let s = "ab".to_string();
let k = 2;
let result = "".to_string();
assert_eq!(Solution::longest_subsequence_repeated_k(s, k), result);
}
}
// Accepted solution for LeetCode #2014: Longest Subsequence Repeated k Times
function longestSubsequenceRepeatedK(s: string, k: number): string {
const check = (t: string, k: number): boolean => {
let i = 0;
for (const c of s) {
if (c === t[i]) {
i++;
if (i === t.length) {
k--;
if (k === 0) {
return true;
}
i = 0;
}
}
}
return false;
};
const cnt = new Array(26).fill(0);
for (const c of s) {
cnt[c.charCodeAt(0) - 97]++;
}
const cs: string[] = [];
for (let i = 0; i < 26; ++i) {
if (cnt[i] >= k) {
cs.push(String.fromCharCode(97 + i));
}
}
const q: string[] = [''];
let ans = '';
while (q.length > 0) {
const cur = q.shift()!;
for (const c of cs) {
const nxt = cur + c;
if (check(nxt, k)) {
ans = nxt;
q.push(nxt);
}
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.