Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 132 Palindrome Partitioning II - Implementation

The code

Phase 11: Build isPalin table. Iterate by length. isPalin[i][i]isPalin[i][i] = true. isPalin[i][i+1]isPalin[i][i+1] = (s[i]s[i] == s[i+1]s[i+1]). For longer: check ends match and inner is palindrome.

Phase 22: Compute cuts[i]cuts[i] for each position. Check if whole prefix is palindrome (00 cuts). Otherwise try all valid last palindrome positions. Answer is cuts[n1]cuts[n-1]. Time: O(n2)O(n^2), Space: O(n2)O(n^2) for isPalin table. Trace through a small example to verify your understanding before moving on.

Time complexity: O(n2)O(n^2).

Space complexity: O(n2)O(n^2).