Problem Description
Given a string s and a positive integer k, select a set of non-overlapping substrings from s such that each substring has length at least k and is a palindrome. Return the maximum number of substrings in an optimal selection. A substring is a contiguous sequence of characters within s.
Key Insights
- We need substrings to be palindromes and their lengths must be at least k.
- To maximize the count, it is beneficial to select the shortest valid palindrome starting at a given index.
- A dynamic programming (DP) approach can precompute if any substring s[i...j] is a palindrome in O(n²) time.
- A greedy strategy is then used to move through the string: at the current index, find the earliest ending palindrome (of length at least k) and jump to its end + 1.
- This two-phase approach (DP for palindromic checks and greedy selection) ensures the selected substrings are non-overlapping and maximizes their count.
Space and Time Complexity
Time Complexity: O(n²) due to the DP precomputation for palindromic substrings. Space Complexity: O(n²) for storing the DP table.
Solution
The solution consists of two main parts. First, we precompute a DP table where dp[i][j] indicates whether the substring from index i to j is a palindrome. This is done by:
- Marking all single characters as palindromes.
- Checking substrings of length 2.
- Using the recurrence relation for longer substrings: a substring is a palindrome if its end characters match and the inner substring is also a palindrome.
Once the DP table is built, we iterate from left to right in the string using a greedy strategy. At each index i, we search for the smallest j (starting from i+k-1) such that dp[i][j] is true. When found, we count that substring and jump to index j+1 to ensure non-overlapping. If no such substring starts at i, we increment i by 1 and try again. This guarantees the maximum number of non-overlapping palindrome substrings is found.