# Longest Palindromic Substring

Today, we will discover one of the basics algorithms to find the longest palindromic substring.

Problem:
Given a string S, find the longest palindromic substring in S.

Difficulty: Easy

Practice: Leetcode

Examples:

```1. S = "abad", Result = "aba"
2. S = "codeedoc", Result = "codeedoc"
```

Solution:
To come up with a solution we need to understand what the palindrome is. Basically, this is just a word which reads the same backward as forward (for more details see).

The main idea is to find all palindromes in S with even and odd lengths and keep track which one is the longest. To find odd length palindromes we fix center for every letter in S and expand it in both directions.

To find even length palindrome we fix center between two nearby letters in S and also expand it in both directions.

While expanding, if two opposite letters are equal then we add them to our potential palindrome.

Time complexity: `O(N^2)`
Space complexity: `O(1)`

That’s all for today. You can find the source code here, but I suggest you implement it by yourself.

Thank you for reading my blog and see you in a leaderboard :)

# Longest Common Substring

In this post, we will discover the basic algorithm to find the longest common substring of two strings.

Problem: Given two strings `X` and `Y`, find the longest common substring.

Difficulty: Easy

Examples:

```1. X = "timetocode", Y = "timerightnow", Result = "time"
2. X = "abcabdef", Y = "abdf", Result = "abd"
```

Solution: Dynamic Programming
To solve this problem, we need to find all occurrences of all `X` letters in `Y` string. To keep intermediate results we can use a two-dimensional array of length `X` and `Y` accordingly.

Even now we can see the result. But to make it more clear, let’s add some rules how to fill this table:
1. If X letter is not equal to Y letter then `Table[i][j] = 0`.
2. If X letter is equal to Y letter then this is already common substring of length 1. If the previous letter was also substring then the length of a new substring is `Table[i][j] = Table[i - 1][j - 1] + 1` (prev length + current length).

Obviously, the length of the longest common substring is the maximum value in this table. And the actual substring can be reproduced by previous cells from the cell with maximum value to the cell with a value of one.

Time complexity: `O(N^2)`
Space complexity: `O(|X| * |Y|)`

The source code for this problem you may find here. Thank you for reading my blog and have a nice coding!