Maximum Number of Non-overlapping Palindrome Substrings - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abccba", k = 3
Output: 1
💡 Note: We can select "bccb" (indices 1-4) or "abccba" (indices 0-5), both are palindromes of length ≥ 3. Maximum is 1.
Example 2 — Multiple Palindromes
$ Input: s = "ababa", k = 3
Output: 2
💡 Note: We can select "aba" (0-2) and "aba" (2-4). They are non-overlapping palindromes of length ≥ 3. Total: 2.
Example 3 — No Valid Palindromes
$ Input: s = "abc", k = 4
Output: 0
💡 Note: String length is 3, but we need palindromes of length ≥ 4. No valid palindromes exist.

Constraints

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

Visualization

Tap to expand
Maximum Non-overlapping Palindrome SubstringsFind maximum count of non-overlapping palindromes of length ≥ kr a c e a c a r0 1 2 3 4 5 6 7Input: s = "raceacar", k = 3"aca" (1-3)"aceac" (1-5)"aca" (4-6)Found palindromes: "aca"(1-3), "aceac"(1-5), "aca"(4-6)Select: "aca"(1-3) and "aca"(4-6) - no overlapSkip: "aceac"(1-5) - overlaps with selected palindromesOutput: 2
Understanding the Visualization
1
Input
String s and minimum length k
2
Find Palindromes
Identify all palindromic substrings of length ≥ k
3
Select Non-overlapping
Greedily select maximum non-overlapping palindromes
Key Takeaway
🎯 Key Insight: Greedy selection of earliest-ending palindromes maximizes the total count
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
68.0K Views
Medium Frequency
~25 min Avg. Time
1.9K 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