← Back to Codes

2026-06-09 16:36:42

Longest Palindromic Substring in Python and Java | LeetCode #5

Learn how to solve Longest Palindromic Substring in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Longest Palindromic Substring in Python and Java

In this tutorial, we will learn LeetCode #5: Longest Palindromic Substring in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Longest Palindromic Substring Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use expand around center because it gives a clean and optimized solution.

Example input:
s = "forgeeksskeegfor"

Expected result:
Output: "geeksskeeg"

Explanation:
This is the longest palindromic substring.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
s = "forgeeksskeegfor"

Approach:
expand around center

We update variables step by step until we reach:
Output: "geeksskeeg"

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why expand around center is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

s = "forgeeksskeegfor"

We will solve it using expand around center.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: "geeksskeeg"

Why?
This is the longest palindromic substring.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: "geeksskeeg"

Example 1

Input:
s = "forgeeksskeegfor"

Output:
Output: "geeksskeeg"

Explanation:
This is the longest palindromic substring.

Example 2

Input:
s = "forgeeksskeegfor"

Output:
"geeksskeeg"

Explanation:
This is the longest palindromic substring.

Python Code

Here is the complete Python solution for LeetCode #5.

class LongestPalindromeFinder:
    def longest_palindrome(self, text):
        best = ""

        def expand(left, right):
            while left >= 0 and right < len(text) and text[left] == text[right]:
                left -= 1
                right += 1
            return text[left + 1:right]

        for index in range(len(text)):
            odd = expand(index, index)
            even = expand(index, index + 1)
            best = max(best, odd, even, key=len)

        return best


finder = LongestPalindromeFinder()
print(finder.longest_palindrome("cabbad"))  # Output: abba
print(finder.longest_palindrome("racecarx"))  # Output: racecar

Java Code

Here is the complete Java solution for LeetCode #5.

class LongestPalindromeFinder {
    public String longestPalindrome(String text) {
        String best = "";

        for (int index = 0; index < text.length(); index++) {
            String odd = expand(text, index, index);
            String even = expand(text, index, index + 1);

            if (odd.length() > best.length()) best = odd;
            if (even.length() > best.length()) best = even;
        }

        return best;
    }

    private String expand(String text, int left, int right) {
        while (left >= 0 && right < text.length() && text.charAt(left) == text.charAt(right)) {
            left--;
            right++;
        }
        return text.substring(left + 1, right);
    }

    public static void main(String[] args) {
        LongestPalindromeFinder finder = new LongestPalindromeFinder();
        System.out.println(finder.longestPalindrome("cabbad"));   // abba
        System.out.println(finder.longestPalindrome("racecarx")); // racecar
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #5: Longest Palindromic Substring becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.