# Longest Palindromic Substring | Set 1

Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”.

## Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

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^3 )
Auxiliary complexity: O ( 1 )

Method 2 ( Dynamic Programming )
The time complexity can be reduced by storing results of subproblems. The idea is similar to this post. 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.

## C

```// A dynamic programming solution for longest palindr.
// This code is adopted from following link
// http://www.leetcode.com/2011/11/longest-palindromic-substring-part-i.html

#include <stdio.h>
#include <string.h>

// A utility function to print a substring str[low..high]
void printSubStr( char* str, int low, int high )
{
for( int i = low; i <= high; ++i )
printf("%c", str[i]);
}

// This function prints the longest palindrome substring
// of str[].
// It also returns the length of the longest palindrome
int longestPalSubstr( char *str )
{
int n = strlen( str ); // get length of input string

// table[i][j] will be false if substring str[i..j]
// is not palindrome.
// Else table[i][j] will be true
bool table[n][n];
memset(table, 0, sizeof(table));

// All substrings of length 1 are palindromes
int maxLength = 1;
for (int i = 0; i < n; ++i)
table[i][i] = true;

// check for sub-string of length 2.
int start = 0;
for (int i = 0; i < n-1; ++i)
{
if (str[i] == str[i+1])
{
table[i][i+1] = true;
start = i;
maxLength = 2;
}
}

// Check for lengths greater than 2. k is length
// of substring
for (int k = 3; k <= n; ++k)
{
// Fix the starting index
for (int i = 0; i < n-k+1 ; ++i)
{
// Get the ending index of substring from
// starting index i and length k
int j = i + k - 1;

// checking for sub-string from ith index to
// jth index iff str[i+1] to str[j-1] is a
// palindrome
if (table[i+1][j-1] && str[i] == str[j])
{
table[i][j] = true;

if (k > maxLength)
{
start = i;
maxLength = k;
}
}
}
}

printf("Longest palindrome substring is: ");
printSubStr( str, start, start + maxLength - 1 );

return maxLength; // return length of LPS
}

// Driver program to test above functions
int main()
{
char str[] = "forgeeksskeegfor";
printf("nLength is: %dn", longestPalSubstr( str ) );
return 0;
}
```

## Java

```// Java Solution
public class LongestPalinSubstring
{
// A utility function to print a substring str[low..high]
static void printSubStr(String str, int low, int high) {
System.out.println(str.substring(low, high + 1));
}

// This function prints the longest palindrome substring
// of str[].
// It also returns the length of the longest palindrome
static int longestPalSubstr(String str) {
int n = str.length();   // get length of input string

// table[i][j] will be false if substring str[i..j]
// is not palindrome.
// Else table[i][j] will be true
boolean table[][] = new boolean[n][n];

// All substrings of length 1 are palindromes
int maxLength = 1;
for (int i = 0; i < n; ++i)
table[i][i] = true;

// check for sub-string of length 2.
int start = 0;
for (int i = 0; i < n - 1; ++i) {
if (str.charAt(i) == str.charAt(i + 1)) {
table[i][i + 1] = true;
start = i;
maxLength = 2;
}
}

// Check for lengths greater than 2. k is length
// of substring
for (int k = 3; k <= n; ++k) {

// Fix the starting index
for (int i = 0; i < n - k + 1; ++i)
{
// Get the ending index of substring from
// starting index i and length k
int j = i + k - 1;

// checking for sub-string from ith index to
// jth index iff str.charAt(i+1) to
// str.charAt(j-1) is a palindrome
if (table[i + 1][j - 1] && str.charAt(i) ==
str.charAt(j)) {
table[i][j] = true;

if (k > maxLength) {
start = i;
maxLength = k;
}
}
}
}
System.out.print("Longest palindrome substring is; ");
printSubStr(str, start, start + maxLength - 1);

return maxLength; // return length of LPS
}

// Driver program to test above functions
public static void main(String[] args) {

String str = "forgeeksskeegfor";
System.out.println("Length is: " +
longestPalSubstr(str));
}
}

// This code is contributed by Sumit Ghosh
```

## Python

```# Python program

import sys

# A utility function to print a
# substring str[low..high]
def printSubStr(st,low,high) :
sys.stdout.write(st[low : high + 1])
sys.stdout.flush()
return ''

# This function prints the longest palindrome
# substring of st[]. It also returns the length
# of the longest palindrome
def longestPalSubstr(st) :
n = len(st) # get length of input string

# table[i][j] will be false if substring
# str[i..j] is not palindrome. Else
# table[i][j] will be true
table = [[0 for x in range(n)] for y
in range(n)]

# All substrings of length 1 are
# palindromes
maxLength = 1
i = 0
while (i < n) :
table[i][i] = True
i = i + 1

# check for sub-string of length 2.
start = 0
i = 0
while i < n - 1 :
if (st[i] == st[i + 1]) :
table[i][i + 1] = True
start = i
maxLength = 2
i = i + 1

# Check for lengths greater than 2.
# k is length of substring
k = 3
while k <= n :
# Fix the starting index
i = 0
while i < (n - k + 1) :

# Get the ending index of
# substring from starting
# index i and length k
j = i + k - 1

# checking for sub-string from
# ith index to jth index iff
# st[i+1] to st[(j-1)] is a
# palindrome
if (table[i + 1][j - 1] and
st[i] == st[j]) :
table[i][j] = True

if (k > maxLength) :
start = i
maxLength = k
i = i + 1
k = k + 1
print "Longest palindrome substring is: ",printSubStr(st, start,
start + maxLength - 1)

return maxLength # return length of LPS

# Driver program to test above functions
st = "forgeeksskeegfor"
l = longestPalSubstr(st)
print "Length is:", l

# This code is contributed by Nikita Tiwari.
```

Output:
```Longest palindrome substring is: geeksskeeg
Length is: 10```

Time complexity: O ( n^2 )
Auxiliary Space: O ( n^2 )

### Asked in: Accolite,Amazon,Groupon,Microsoft

We will soon be adding more optimized methods as separate posts.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
3.5 Average Difficulty : 3.5/5.0
Based on 174 vote(s)

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.