You are given a string s and a positive integer k.
Select a set of non-overlapping substrings from the string s that satisfy the following conditions:
The length of each substring is at leastk.
Each substring is a palindrome.
Return the maximum number of substrings in an optimal selection.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "abaccdbbd", k = 3
Output: 2
Explanation: We can select the substrings underlined in s = "abaccdbbd". Both "aba" and "dbbd" are palindromes and have a length of at least k = 3.
It can be shown that we cannot find a selection with more than two valid substrings.
Example 2:
Input: s = "adbcda", k = 2
Output: 0
Explanation: There is no palindrome substring of length at least 2 in the string.
Problem summary: You are given a string s and a positive integer k. Select a set of non-overlapping substrings from the string s that satisfy the following conditions: The length of each substring is at least k. Each substring is a palindrome. Return the maximum number of substrings in an optimal selection. A substring is a contiguous sequence of characters within a string.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers · Dynamic Programming · Greedy
Palindrome Partitioning II (palindrome-partitioning-ii)
Palindrome Partitioning III (palindrome-partitioning-iii)
Maximum Number of Non-Overlapping Substrings (maximum-number-of-non-overlapping-substrings)
Step 02
Core Insight
What unlocks the optimal approach
Try to use dynamic programming to solve the problem.
let dp[i] be the answer for the prefix s[0…i].
The final answer to the problem will be dp[n-1]. How do you compute this dp?
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2472: Maximum Number of Non-overlapping Palindrome Substrings
class Solution {
private boolean[][] dp;
private int[] f;
private String s;
private int n;
private int k;
public int maxPalindromes(String s, int k) {
n = s.length();
f = new int[n];
this.s = s;
this.k = k;
dp = new boolean[n][n];
for (int i = 0; i < n; ++i) {
Arrays.fill(dp[i], true);
f[i] = -1;
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
dp[i][j] = s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1];
}
}
return dfs(0);
}
private int dfs(int i) {
if (i >= n) {
return 0;
}
if (f[i] != -1) {
return f[i];
}
int ans = dfs(i + 1);
for (int j = i + k - 1; j < n; ++j) {
if (dp[i][j]) {
ans = Math.max(ans, 1 + dfs(j + 1));
}
}
f[i] = ans;
return ans;
}
}
// Accepted solution for LeetCode #2472: Maximum Number of Non-overlapping Palindrome Substrings
func maxPalindromes(s string, k int) int {
n := len(s)
dp := make([][]bool, n)
f := make([]int, n)
for i := 0; i < n; i++ {
dp[i] = make([]bool, n)
f[i] = -1
for j := 0; j < n; j++ {
dp[i][j] = true
}
}
for i := n - 1; i >= 0; i-- {
for j := i + 1; j < n; j++ {
dp[i][j] = s[i] == s[j] && dp[i+1][j-1]
}
}
var dfs func(int) int
dfs = func(i int) int {
if i >= n {
return 0
}
if f[i] != -1 {
return f[i]
}
ans := dfs(i + 1)
for j := i + k - 1; j < n; j++ {
if dp[i][j] {
ans = max(ans, 1+dfs(j+1))
}
}
f[i] = ans
return ans
}
return dfs(0)
}
# Accepted solution for LeetCode #2472: Maximum Number of Non-overlapping Palindrome Substrings
class Solution:
def maxPalindromes(self, s: str, k: int) -> int:
@cache
def dfs(i):
if i >= n:
return 0
ans = dfs(i + 1)
for j in range(i + k - 1, n):
if dp[i][j]:
ans = max(ans, 1 + dfs(j + 1))
return ans
n = len(s)
dp = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
dp[i][j] = s[i] == s[j] and dp[i + 1][j - 1]
ans = dfs(0)
dfs.cache_clear()
return ans
// Accepted solution for LeetCode #2472: Maximum Number of Non-overlapping Palindrome Substrings
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2472: Maximum Number of Non-overlapping Palindrome Substrings
// class Solution {
// private boolean[][] dp;
// private int[] f;
// private String s;
// private int n;
// private int k;
//
// public int maxPalindromes(String s, int k) {
// n = s.length();
// f = new int[n];
// this.s = s;
// this.k = k;
// dp = new boolean[n][n];
// for (int i = 0; i < n; ++i) {
// Arrays.fill(dp[i], true);
// f[i] = -1;
// }
// for (int i = n - 1; i >= 0; --i) {
// for (int j = i + 1; j < n; ++j) {
// dp[i][j] = s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1];
// }
// }
// return dfs(0);
// }
//
// private int dfs(int i) {
// if (i >= n) {
// return 0;
// }
// if (f[i] != -1) {
// return f[i];
// }
// int ans = dfs(i + 1);
// for (int j = i + k - 1; j < n; ++j) {
// if (dp[i][j]) {
// ans = Math.max(ans, 1 + dfs(j + 1));
// }
// }
// f[i] = ans;
// return ans;
// }
// }
// Accepted solution for LeetCode #2472: Maximum Number of Non-overlapping Palindrome Substrings
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2472: Maximum Number of Non-overlapping Palindrome Substrings
// class Solution {
// private boolean[][] dp;
// private int[] f;
// private String s;
// private int n;
// private int k;
//
// public int maxPalindromes(String s, int k) {
// n = s.length();
// f = new int[n];
// this.s = s;
// this.k = k;
// dp = new boolean[n][n];
// for (int i = 0; i < n; ++i) {
// Arrays.fill(dp[i], true);
// f[i] = -1;
// }
// for (int i = n - 1; i >= 0; --i) {
// for (int j = i + 1; j < n; ++j) {
// dp[i][j] = s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1];
// }
// }
// return dfs(0);
// }
//
// private int dfs(int i) {
// if (i >= n) {
// return 0;
// }
// if (f[i] != -1) {
// return f[i];
// }
// int ans = dfs(i + 1);
// for (int j = i + k - 1; j < n; ++j) {
// if (dp[i][j]) {
// ans = Math.max(ans, 1 + dfs(j + 1));
// }
// }
// f[i] = ans;
// return ans;
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n^2)
Space
O(n^2)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
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.
TWO POINTERS
O(n) time
O(1) space
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.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
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.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.