Longest Palindromic Substring

Prince Pereira
2 min readAug 9, 2020

Find the longest palindromic substring from a long string.

  1. Iterate from i := 1 to i := n-1 considering i^th value as the center of Palindromic substring.
  2. Iterating from the ith value towards left and right, look for an even length palindromic substring.
    Eg: abcddcaa
    Longest palindromic substring is : cddc
  3. Iterating from the ith value towards left and right, look for an even length palindromic substring.
    Eg: xyxabcdcba
    Longest palindromic substring is : abcdcba
  4. After identifying each palindrome string, compare with previously identified value and replace.
package mainimport "fmt"func main() {
str := "abcxxyyxxdef"
palindrome := ""
for i := 1; i < len(str)-1; i++ {
if tmpPalindrome := getPalindromicSubstr(str, i, true); tmpPalindrome != "" && len(tmpPalindrome) > len(palindrome) {
palindrome = tmpPalindrome
}
if tmpPalindrome := getPalindromicSubstr(str, i, false); tmpPalindrome != "" && len(tmpPalindrome) > len(palindrome) {
palindrome = tmpPalindrome
}
}
if palindrome == ""{
palindrome = str[:1]
}
fmt.Println("Longest palindromic substring : ", palindrome)
}
func getPalindromicSubstr(str string, idx int, odd bool) string {
lenStr := len(str)
palindrome := ""
var i, j int
if odd {
i = idx - 1
j = idx + 1
} else {
i = idx - 1
j = idx
}
for i >= 0 && j < lenStr {
if tmp, ok := isPalindrome(str, i, j); ok {
palindrome = tmp
i--
j++
} else {
return palindrome
}
}
return palindrome
}
func isPalindrome(str string, idxStart, idxEnd int) (string, bool) {
subStr := str[idxStart : idxEnd+1]
lastIdx := len(subStr) - 1
for i := 0; i < lastIdx/2 && i < (lastIdx-i); i++ {
if subStr[i] != subStr[lastIdx-i] {
return "", false
}
}
return subStr, true
}

Time Complexity : O(n2)
Space Complexity : O(1)

--

--

Prince Pereira

Senior Software Engineer - Microsoft | SDN | Java | Golang | DS & Algo | Microservices | Kubernetes | Docker | gRPC & Protocol Buffer