Skip to content

Added code for palindrome partitioning problem under dynamic programming #7222

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Oct 30, 2022
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions dynamic_programming/palindrome_partitioning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
Given a string s, partition s such that every substring of the
partition is a palindrome.
Find the minimum cuts needed for a palindrome partitioning of s.

Time Complexity: O(n^2)
Space Complexity: O(n^2)
For other explanations refer to: https://www.youtube.com/watch?v=_H8V5hJUGd0
"""


def find_minimum_partitions(string: str) -> int:
"""
Returns the minimum cuts needed for a palindrome partitioning of string

>>> find_minimum_partitions("aab")
1
>>> find_minimum_partitions("aaa")
0
>>> find_minimum_partitions("ababbbabbababa")
3
"""
length = len(string)
cut = [0] * length
is_palindromic = [[False for i in range(length)] for j in range(length)]
for i, c in enumerate(length):
mincut = i
for j in range(i + 1):
if c == string[j] and (i - j < 2 or ispalindrome[j + 1][i - 1]):
is_palindromic[j][i] = True
mincut = min(mincut, 0 if j == 0 else (cut[j - 1] + 1))
cut[i] = mincut
return cut[n - 1]


if __name__ == "__main__":
s = input("Enter the string: ").strip()
ans = find_minimum_partitions(s)
print(f"Minimum number of partitions required for the '{s}' is {ans}")