Talentd
FleetCode
Make and follow sheets.Sign in

Longest Subsequence Repeated k Times solution and explanation

HardBacktrackingCountingEnumerationGreedy8 min read71.3% acceptanceUpdated 9 Apr 2026
Longest Subsequence Repeated k Times | 2 Ways To Code | Detailed | Leetcode 2014 | codestorywithMIKcodestorywithMIK · 48:15 · 10K viewsWatch on YouTube
9 more videos on this problem
  1. Longest Subsequence Repeated k Times | 2 Ways To Code | Detailed | Leetcode 2014 | codestorywithMIKcodestorywithMIK · 48:15 · 10K views
  2. LeetCode 2014. Longest Subsequence Repeated k TimesHappy Coding · 31:36 · 3K views
  3. Longest Subsequence Repeated k Times | Leetcode 2014Techdose · 26:42 · 3K views
  4. 2014. Longest Subsequence Repeated k Times (Leetcode Hard)Programming Live with Larry · 43:23 · 1K views
  5. 2014. Longest Subsequence Repeated k Times | Leetcode Daily - PythonLeetcode Daily · 6:42 · 959 views
  6. 2014. Longest Subsequence Repeated k Times | LeetCode 2014 | Java BFS Solution ExplainedcodingX krishna · 34:35 · 367 views
  7. Longest Subsequence Repeated k Times | Leetcode 2014 | LeetCode Hard | Java Code | Developer CoderDeveloper Coder · 30:42 · 166 views
  8. LeetCode 2014 Longest Subsequence Repeated k Times | Greedy | BackTracking | Asked in MetaCode Harmony · 28:10 · 146 views
  9. Leetcode 2014 Longest Subsequence Repeated k Times带老婆转码 · 15:56 · 104 views
  10. Leetcode Longest Subsequence Repeated k Times attemptVMS CODE · 3:01:57 · 91 views

The 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.

Example 1:

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.length
  • 2 <= n, k <= 2000
  • 2 <= n < k * 8
  • s consists of lowercase English letters.

Approach overview

Problem Overview: Given a string s and an integer k, find the longest subsequence that appears at least k times in s. The subsequences can overlap, but the order of characters must remain the same. If multiple answers exist with the same length, return the lexicographically largest one.

Approach 1: Backtracking with Pruning (Time: roughly O(26^m * n), Space: O(m))

This approach treats the result as a candidate string and builds it character by character using backtracking. First count character frequencies using counting. A character can only appear in the answer if its frequency in s is at least k. Build candidates using only those valid characters. During recursion, append a character, then check whether the candidate repeated k times is still a subsequence of s. If it fails, prune that branch immediately. This pruning drastically reduces the search space because invalid prefixes never expand further. To check subsequences efficiently, iterate through s and greedily match characters.

The key insight: the maximum length of the answer is small because each character must appear at least k times in the string. That constraint keeps the search manageable. Backtracking also tries characters in reverse lexicographic order so the first valid longest candidate becomes the final answer.

Approach 2: Iterative Search with Pre-filtering (Time: ~O(C^m * n), Space: O(C))

This method avoids deep recursion and instead performs iterative candidate expansion. Start by computing frequencies of characters in the string. Only characters with frequency ≥ k are allowed in the candidate pool. Build possible subsequences level by level: start with single characters, then extend them by appending valid characters. For every candidate, check whether repeating it k times forms a subsequence of s. Invalid candidates are discarded early.

The greedy element appears when exploring candidates in descending lexicographic order. Since the goal is the longest and lexicographically largest subsequence, maintaining that ordering ensures better candidates are evaluated first. Pre-filtering significantly reduces the alphabet size, which keeps the enumeration manageable.

This iterative search works well in languages like C++ or JavaScript where queue-based enumeration is straightforward and recursion limits might be undesirable. The subsequence validation step still uses a linear scan over s, matching characters in order.

Recommended for interviews: Backtracking with pruning is the approach most interviewers expect. It demonstrates understanding of subsequence validation, search space reduction, and frequency-based pruning. The iterative enumeration variant shows the same idea implemented without recursion and is useful when discussing optimization or language-specific constraints.

Approach 1: Approach 1: Backtracking with Pruning

This approach constructs possible subsequences character by character using backtracking. We try potential subsequences in a lexicographical order and if a subsequence can be repeated k times and is still a subsequence of s, we record it.

We use a recursive function to generate possible subsequences, trying to append characters in a way that ensures the subsequences generated remain valid candidates. Each generated candidate is verified by checking if it can form a subsequence that repeats k times.

def check(seq, s, k):
    it = iter(s)
    return sum(seq == ''.join(x) for x in zip(*[it] * k)) >= 1

def backtrack(chars, s, k, current):
    if not check(current * k, s, k):
        return ''
    longest = current
    for c in chars:
        candidate = backtrack(chars, s, k, current + c)
        if len(candidate) > len(longest) or (len(candidate) == len(longest) and candidate > longest):
            longest = candidate
    return longest

def longest_subsequence_repeated_k(s, k):
    from collections import Counter
    counter = Counter(s)
    chars = sorted([c for c in counter if counter[c] >= k], reverse=True)
    return backtrack(chars, s, k, '')
import java.util.*;

public class Solution {
    public String longestSubsequenceRepeatedK(String s, int k) {
        Map<Character, Integer> freq = new HashMap<>();
        for (char c : s.toCharArray()) {
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        }
        List<Character> chars = new ArrayList<>();
        for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
            if (entry.getValue() / k > 0) {
                chars.add(entry.getKey());
            }
        }
        Collections.sort(chars, Collections.reverseOrder());
        return backtrack(s, new StringBuilder(), k, chars);
    }

    private String backtrack(String s, StringBuilder current, int k, List<Character> chars) {
        if (!check(s, current.toString(), k)) {
            return "";
        }
        String result = current.toString();
        for (char c : chars) {
            current.append(c);
            String candidate = backtrack(s, current, k, chars);
            current.deleteCharAt(current.length() - 1);
            if (candidate.length() > result.length() || (candidate.length() == result.length() && candidate.compareTo(result) > 0)) {
                result = candidate;
            }
        }
        return result;
    }

    private boolean check(String s, String seq, int k) {
        int seqLen = seq.length();
        int totalLen = seqLen * k;
        if (totalLen > s.length()) {
            return false;
        }
        int j = 0;
        for (int i = 0; i < s.length() && j < totalLen; i++) {
            if (s.charAt(i) == seq.charAt(j % seqLen)) {
                j++;
            }
        }
        return j >= totalLen;
    }
}

The backtracking function is implemented to explore all possible subsequences. We use a helper function check to determine if a candidate subsequence can repeat k times within s. The characters are sorted in reverse lexicographical order to ensure we find the lexicographically largest subsequence.

Complexity

Time Complexity: O(2^n), where n is the length of the string due to the generation of subsequences.

Space Complexity: O(n) due to recursion and additional data structures.

Try this approach in the editor

Approach 2: Approach 2: Iterative Search with Pre-filtering

This approach begins by pre-filtering characters and possible subsequences based on their frequency in s. Then it uses an iterative search to evaluate each candidate, starting from the most frequently appearing characters and growing subsequences by iteratively adding characters.

The sequence group is filtered and expanded iteratively to ensure that invalid paths are quickly discarded, making the search efficient.

#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    string longestSubsequenceRepeatedK(string s, int k) {
        unordered_map<char, int> freq;
        for (char c : s) {
            freq[c] += 1;
        }
        vector<char> chars;
        for (const auto &pair : freq) {
            if (pair.second / k > 0) {
                chars.push_back(pair.first);
            }
        }
        sort(chars.begin(), chars.end(), greater<char>());
        string result = "";
        dfs(chars, s, k, "", result);
        return result;
    }

private:
    void dfs(vector<char> &chars, string &s, int k, string current, string &longest) {
        if (check(s, current, k)) {
            if (current.length() > longest.length() || (current.length() == longest.length() && current > longest)) {
                longest = current;
            }
        }
        for (char c : chars) {
            dfs(chars, s, k, current + c, longest);
        }
    }

    bool check(const string &s, const string &seq, int k) {
        int seqLen = seq.length();
        int j = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (s[i] == seq[j % seqLen]) {
                j++;
                if (j == seqLen * k) return true;
            }
        }
        return false;
    }
};
const longestSubsequenceRepeatedK = (s, k) => {
    const freqMap = {};
    for (let char of s) {
        if (!freqMap[char]) freqMap[char] = 0;
        freqMap[char]++;
    }
    const chars = Object.keys(freqMap).filter(c => freqMap[c] >= k).sort().reverse();
    let result = '';

    const check = (str, sub, k) => {
        let j = 0;
        for (let i = 0; i < str.length && j < sub.length * k; i++) {
            if (str[i] === sub[j % sub.length]) j++;
        }
        return j >= sub.length * k;
    };

    const dfs = (s, chars, k, current) => {
        if (!check(s, current, k)) return '';
        let longest = current;
        for (let c of chars) {
            let candidate = dfs(s, chars, k, current + c);
            if (candidate.length > longest.length || (candidate.length === longest.length && candidate > longest)) {
                longest = candidate;
            }
        }
        return longest;
    };

    result = dfs(s, chars, k, '');
    return result;
};

The method first constructs a list of characters that can be part of the repeated subsequence. A depth-first search (DFS) approach is used to evaluate potential subsequences. For each subsequence, we use a check function to verify if it can be a k-repeated subsequence of the given string.

Complexity

Time Complexity: O(2^n), due to the iterative exploration of subsequences.

Space Complexity: O(n) because of the recursion stack and additional data structures used.

Try this approach in the editor

Approach 3: BFS

We can first count the occurrences of each character in the string, and then store the characters that appear at least k times in a list cs in ascending order. Next, we can use BFS to enumerate all possible subsequences.

We define a queue q, initially putting the empty string into the queue. Then, we take out a string cur from the queue and try to append each character c \in cs to the end of cur to form a new string nxt. If nxt is a subsequence that can be repeated k times, we add it to the answer and put nxt back into the queue for further processing.

We need an auxiliary function check(t, k) to determine whether the string t is a repeated k times subsequence of string s. Specifically, we can use two pointers to traverse s and t. If we can find all characters of t in s and repeat this process k times, then return true; otherwise, return false.

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;
}
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
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Backtracking with Pruning

Time Complexity: O(2^n), where n is the length of the string due to the generation of subsequences.

Space Complexity: O(n) due to recursion and additional data structures.

Approach 2: Iterative Search with Pre-filtering

Time Complexity: O(2^n), due to the iterative exploration of subsequences.

Space Complexity: O(n) because of the recursion stack and additional data structures used.

BFS–

Complexity analysis

ApproachTimeSpaceWhen to Use
Backtracking with Pruning~O(26^m * n)O(m)Best general solution. Pruning removes invalid prefixes early and works well when candidate length is small.
Iterative Search with Pre-filtering~O(C^m * n)O(C)Good when avoiding recursion or implementing breadth-first enumeration in C++/JavaScript.

Frequently asked questions

Is Longest Subsequence Repeated k Times easy or hard?

This problem is classified as Hard because it combines subsequence validation with exponential search. Efficient pruning using character frequencies and lexicographic ordering is necessary to keep the candidate exploration manageable.

Longest Subsequence Repeated k Times Python/Java solution

Python and Java implementations typically use backtracking with pruning. The algorithm builds candidate strings, checks whether candidate * k is a subsequence of s, and updates the best result based on length and lexicographic order. The same logic can also be implemented iteratively in C++ or JavaScript.

How to solve Longest Subsequence Repeated k Times in O(n)?

A strict O(n) solution is not possible because the algorithm must explore candidate subsequences. The practical solution reduces the search space using frequency filtering and pruning. After limiting characters to those appearing at least k times, candidate strings are tested using a linear subsequence check over s.

What is the best approach for Longest Subsequence Repeated k Times?

Backtracking with pruning is the most effective strategy. The algorithm builds candidate subsequences using only characters that appear at least k times in the string. Each candidate is validated by checking if it can appear k times as a subsequence of s. Early pruning removes invalid prefixes, keeping the search space manageable.

Is Longest Subsequence Repeated k Times asked at Google/Amazon/Meta?

Problems involving subsequence enumeration, pruning, and greedy ordering frequently appear in interviews at companies like Google, Amazon, and Meta. Variations of this problem test understanding of backtracking, subsequence validation, and optimization through frequency filtering.

What data structure is used in Longest Subsequence Repeated k Times?

The solution primarily uses a frequency counter (hash map or array) to track character counts and restrict the search alphabet. Backtracking or queue-based enumeration stores candidate subsequences, while a simple pointer scan over the string validates subsequence repetition.

What is the time complexity of Longest Subsequence Repeated k Times?

The complexity is roughly O(26^m * n), where m is the length of the resulting subsequence and n is the length of the input string. Each candidate subsequence is tested by scanning the string once to verify whether it repeats k times. Because characters must appear at least k times, m remains small in practice.

Comments

Now write it yourselfClose this page and solve Longest Subsequence Repeated k Times in the editor, without looking.
Practise Longest Subsequence Repeated k Times