fix: reduce palindrome_partitioning time complexity from O(n^3) to O(n^2)#3171
Open
https-hari wants to merge 1 commit into
Open
fix: reduce palindrome_partitioning time complexity from O(n^3) to O(n^2)#3171https-hari wants to merge 1 commit into
https-hari wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description of Change
The existing implementation claims O(n^2) time complexity in its documentation
but actually runs in O(n^3) due to three nested loops:
Fix
Replaced the 2D cuts table with a 1D DP array
cuts[i], wherecuts[i]= minimum cuts needed for str[0..i].For each position i, we scan j from 1 to i — if str[j..i] is a palindrome,
then cuts[i] = min(cuts[i], cuts[j-1] + 1). This eliminates the third
nested loop entirely, genuinely achieving the O(n^2) complexity the
original code claimed but never delivered.
Complexity
The original had three nested loops making it O(n^3) in time despite claiming
O(n^2) in the docs. This fix brings it down to true O(n^2) by eliminating
the innermost partition loop entirely. Space stays O(n^2) for the palindrome
table, plus a small O(n) for the new 1D cuts array.
Tests Added
two different chars, full palindrome, all same chars, no palindrome substrings
Relates to #2456