Skip to content

fix: reduce palindrome_partitioning time complexity from O(n^3) to O(n^2)#3171

Open
https-hari wants to merge 1 commit into
TheAlgorithms:masterfrom
https-hari:fix/palindrome-partitioning-on2
Open

fix: reduce palindrome_partitioning time complexity from O(n^3) to O(n^2)#3171
https-hari wants to merge 1 commit into
TheAlgorithms:masterfrom
https-hari:fix/palindrome-partitioning-on2

Conversation

@https-hari

Copy link
Copy Markdown

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:

  • Outer loop over lengths: O(n)
  • Inner loop over start indices: O(n)
  • Innermost loop over partition points: O(n)

Fix

Replaced the 2D cuts table with a 1D DP array cuts[i], where
cuts[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

  • Original 3 test cases preserved and passing
  • Added 7 new edge cases: empty string, single char, two same chars,
    two different chars, full palindrome, all same chars, no palindrome substrings

Relates to #2456

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant