Skip to content

Commit

Permalink
Merge pull request #1214 from belikesayantan/master
Browse files Browse the repository at this point in the history
Added Longest Palindromic Substring in Python
  • Loading branch information
jrg94 authored Oct 10, 2019
2 parents a02a70c + 8e1677b commit 589bfd3
Show file tree
Hide file tree
Showing 5 changed files with 120 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ At any rate, if articles sound interesting, here are a few to get you started:
- [Hello World in Every Language][2]
- [Reverse a String in Every Language][3]
- [The Coolest Programming Language Features][4]
- [Longest Palindromic Substring in Every Language][16]

Alternatively, feel free to leverage the links in the README files spread throughout the repository.
In addition, we have a rather extensive [wiki][5] which includes a table row for every language
Expand Down Expand Up @@ -84,3 +85,4 @@ Thanks for your support! :relaxed:
[13]: https://help.getadblock.com/support/solutions/articles/6000163989-how-do-i-pause-or-disable-adblock-
[14]: https://twitter.com/RenegadeCoder94
[15]: https://gitter.im/TheRenegadeCoder/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link
[16]: https://therenegadecoder.com/code/longest-palindrome-substring-in-every-language/
1 change: 1 addition & 0 deletions archive/p/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Welcome to Sample Programs in Python!
- [Insertion Sort in Python][34]
- [Job Sequencing with Deadlines in Python][30]
- [Longest Common Subsequence][26]
- [Longest Palindromic Subsequence][42]
- [Merge Sort in Python][35]
- [Prime Number in Python][36]
- [Quick Sort in Python][37]
Expand Down
38 changes: 38 additions & 0 deletions archive/p/python/longest_palindrome_substring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
Given a string S, find the longest palindromic substring in S.
"""
def longestPalindrome(string):
longest = ""

centres = [len(string) - 1]
for diff in range(1, len(string)):
centres.append(centres[0] + diff)
centres.append(centres[0] - diff)

for centre in centres:

if(min(centre + 1, 2 * len(string) - 1 - centre) <= len(longest)):
break
if centre % 2 == 0:
left, right = (centre // 2) - 1, (centre // 2) + 1
else:
left, right = centre // 2, (centre // 2) + 1

while left >= 0 and right < len(string) and string[left] == string[right]:
left -= 1
right += 1

if right - left > len(longest):
longest = string[left + 1: right]

return longest

if __name__ == '__main__':
string = str(input("Enter String: "))
if string == "" and string == None:
print("Incorrect input provided. Program Terminated")
sub = longestPalindrome(string)
if len(sub) == 1:
print("No Palindromic substring present.")
else:
print("Longest Palindromic Substring is: {}".format(sub))
Binary file modified docs/assets/images/fizz-buzz.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
79 changes: 79 additions & 0 deletions docs/projects/longest-palindrome-substring/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
title: Longest Palindromic Substring in Every Language
layout: default
date: 2019-10-08
last-modified: 2018-10-09
featured-image:
tags: [longest-palindrome-substring]
authors:
- Sayantan Paul
---

Given a string, we need to find the smallest substring inside the main string which is a palindrome.

## Description

Palindrome is a phenomenon, where a string has same sequence of letters when read start --> end and end --> start.

Let's say we have a string,

```
s = 'paapaapap'
```

Here, we have seven palindromic substrings.

```
sub_1 = 'aa'
sub_2 = 'paap'
sub_3 = 'paapaap'
sub_4 = 'aapaa'
sub_5 = 'apap'
sub_6 = 'pap'
sub_7 = 'apaapa'
```

Out of the seven, `sub_3 = 'paapaap'` is the longest. hence the output would be `'paapaap'`

## Requirements

This problem can be solved using 3 methods.

### Method 1 ( Brute Force )

The simple approach is to check each substring whether the substring is a palindrome or not. We can run three loops, the outer two loops pick all substrings one by one by fixing the corner characters, the inner loop checks whether the picked substring is palindrome or not.

- Time complexity: O (n<sup>3</sup>)
- Auxiliary complexity: O (1)

### Method 2 ( Dynamic Programming )

The time complexity can be reduced by storing results of subproblems. We maintain a boolean table[n][n] that is filled in bottom up manner. The value of table[i][j] is true, if the substring is palindrome, otherwise false. To calculate table[i][j], we first check the value of table[i+1][j-1], if the value is true and str[i] is same as str[j], then we make table[i][j] true. Otherwise, the value of table[i][j] is made false.
- Time complexity: O ( n^2 )
- Auxiliary Space: O ( n^2 )

### Method 3

The time complexity of the Dynamic Programming based solution is O(n<sup>2</sup>) and it requires O(n<sup>2</sup>) extra space. We can find the longest palindrome substring in (n<sup>2</sup>) time with O(1) extra space. The idea is to generate all even length and odd length palindromes and keep track of the longest palindrome seen so far.

#### Step to generate odd length palindrome:

Fix a centre and expand in both directions for longer palindromes.

#### Step to generate even length palindrome

Fix two centre ( low and high ) and expand in both directions for longer palindromes.
- Time complexity: O (n<sup>2</sup>) where n is the length of input string.
- Auxiliary Space: O ( 1 )

## Testing

The following table contains various test cases that you can use to verify the correctness of your solution:

| Description | Input | Output |
|-------------|-------|--------|
| No Input | |"Incorrect input provided. Program Terminated"|
|Empty String|""|"Incorrect input provided. Program Terminated"|
|Non-Palindromic string with initial capital letters|"Polip"|"No Palindromic substring present."|
|Palindromic string with disordered casing|"BoOroO"|"No Palindromic substring present."|
|Palindromic string with letters and numerics|"6eie6o6"|"Longest Palindromic Substring is: 6eie6"|

0 comments on commit 589bfd3

Please sign in to comment.