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".
The key insight is that a character must appear at least k times to be part of any valid subsequence. Best approach uses backtracking with frequency-based pruning to build subsequences systematically while avoiding impossible branches. Time: O(n × 2ᵛ × k), Space: O(n + v)
Common Approaches
✓
Bfs
⏱️ Time: N/A
Space: N/A
Brute Force Enumeration
⏱️ Time: O(2ⁿ × n × k)
Space: O(n)
Generate all possible subsequences of the string, then for each subsequence check if concatenating it k times forms a valid subsequence of the original string. Keep track of the longest valid subsequence.
Frequency Count with Validation
⏱️ Time: O(n + 2ᵛ × n × k)
Space: O(n + v)
First count how many times each character appears in the string. Only characters that appear at least k times can be part of a valid subsequence. Build candidates by trying all combinations of valid characters.
Optimized Backtracking
⏱️ Time: O(n × 2ᵛ × k)
Space: O(n + v)
Build subsequences incrementally using backtracking. For each position in the original string, decide whether to include that character. Use frequency counting and early pruning to eliminate impossible branches.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int x, y, height;
} Point;
typedef struct {
Point* data;
int front, rear, capacity;
} Queue;
Queue* createQueue(int capacity) {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->data = (Point*)malloc(capacity * sizeof(Point));
q->front = q->rear = 0;
q->capacity = capacity;
return q;
}
void enqueue(Queue* q, Point p) {
q->data[q->rear++] = p;
}
Point dequeue(Queue* q) {
return q->data[q->front++];
}
int isEmpty(Queue* q) {
return q->front == q->rear;
}
int** solution(int** isWater, int isWaterSize, int* isWaterColSize, int* returnSize, int** returnColumnSizes) {
int m = isWaterSize, n = isWaterColSize[0];
int** height = (int**)malloc(m * sizeof(int*));
*returnSize = m;
*returnColumnSizes = (int*)malloc(m * sizeof(int));
Queue* queue = createQueue(m * n);
// Initialize
for (int i = 0; i < m; i++) {
height[i] = (int*)malloc(n * sizeof(int));
(*returnColumnSizes)[i] = n;
for (int j = 0; j < n; j++) {
if (isWater[i][j] == 1) {
Point p = {i, j, 0};
enqueue(queue, p);
height[i][j] = 0;
} else {
height[i][j] = -1; // Mark unvisited land cells
}
}
}
int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// Multi-source BFS
while (!isEmpty(queue)) {
Point curr = dequeue(queue);
for (int d = 0; d < 4; d++) {
int nx = curr.x + directions[d][0];
int ny = curr.y + directions[d][1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && height[nx][ny] == -1) {
height[nx][ny] = curr.height + 1;
Point p = {nx, ny, curr.height + 1};
enqueue(queue, p);
}
}
}
free(queue->data);
free(queue);
return height;
}
int parseArray(char* str, int*** result, int** colSizes) {
// Simple JSON array parser
int len = strlen(str);
if (len < 2) return 0;
// Count rows
int rows = 1;
for (int i = 0; i < len; i++) {
if (str[i] == '[' && i > 0 && str[i-1] != '[') rows++;
}
rows--; // Subtract outer array
*result = (int**)malloc(rows * sizeof(int*));
*colSizes = (int*)malloc(rows * sizeof(int));
int row = 0;
int i = 1; // Skip first '['
while (i < len && row < rows) {
if (str[i] == '[') {
i++;
// Count numbers in this row
int nums = 0;
int j = i;
while (j < len && str[j] != ']') {
if (str[j] >= '0' && str[j] <= '9') {
nums++;
while (j < len && str[j] >= '0' && str[j] <= '9') j++;
} else {
j++;
}
}
(*result)[row] = (int*)malloc(nums * sizeof(int));
(*colSizes)[row] = nums;
// Parse numbers
int col = 0;
while (i < len && str[i] != ']' && col < nums) {
if (str[i] >= '0' && str[i] <= '9') {
(*result)[row][col] = str[i] - '0';
col++;
}
i++;
}
row++;
}
i++;
}
return rows;
}
int main() {
char input[10000];
fgets(input, sizeof(input), stdin);
// Remove newline
int len = strlen(input);
if (len > 0 && input[len-1] == '\n') {
input[len-1] = '\0';
}
int** isWater;
int* colSizes;
int rows = parseArray(input, &isWater, &colSizes);
int returnSize;
int* returnColumnSizes;
int** result = solution(isWater, rows, colSizes, &returnSize, &returnColumnSizes);
// Print result
printf("[");
for (int i = 0; i < returnSize; i++) {
if (i > 0) printf(",");
printf("[");
for (int j = 0; j < returnColumnSizes[i]; j++) {
if (j > 0) printf(",");
printf("%d", result[i][j]);
}
printf("]");
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
⚡ Linearithmic Space
12.5K Views
MediumFrequency
~35 minAvg. Time
487 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.