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: 1
💡 Note: We have palindromes "aba" (0-2) and "aba" (2-4), but they overlap at index 2. We can only select one of them. Maximum is 1.
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
Max Non-overlapping Palindrome Substrings INPUT String s = "abccba" a 0 b 1 c 2 c 3 b 4 a 5 k = 3 Minimum substring length must be 3 Palindrome Candidates: "bccb" (len=4) "abccba" (len=6) "cc" (len=2, skip) Length 6 string ALGORITHM STEPS 1 Scan Left to Right Greedy: find earliest valid palindrome 2 Check Palindrome For each position, check substrings of length >= k 3 Select Shortest Valid Pick shortest palindrome ending earliest 4 Skip Overlapping Move pointer past selected substring Greedy Selection: i=0: "abc" not palindrome i=0: "abcc" not palindrome ...found "abccba" (full) FINAL RESULT Selected Palindrome: "abccba" Full string is a palindrome with length 6 >= k=3 Count: 1 Only one palindrome can be selected (non-overlapping) Output: 1 Key Insight: Greedy approach works because selecting the shortest valid palindrome ending earliest maximizes remaining space for future selections. We scan left-to-right, greedily picking the first palindrome of length >= k, then continue from where it ends. TutorialsPoint - Maximum Number of Non-overlapping Palindrome Substrings | Greedy Approach
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