LeetCode 5 Solution: Longest Palindromic Substring

L

LeetCode 5 Solution – The Longest Palindromic Substring: the problem asks us to find the longest substring within a given string s that reads the same forwards and backwards. A palindrome is a word or sequence of characters that is identical when reversed. For example, in the string "babad", both "bab" and "aba" are palindromic substrings, with a length of 3.

Given a string s, return the longest palindromic substring in s.

Input: s = “babad”
Output: “bab”
Explanation: “aba” is also a valid answer.

Input: s = “cbbd”
Output: “bb”

Constraints:
– 1 <= s.length <= 1000
– s consist of only digits and English letters.

Our goal is to develop an efficient Python solution that can handle strings of up to 1000 characters, as specified by the problem constraints.

Approach Discussion

When tackling this problem, several strategies come to mind. A naive approach would be to check all possible substrings and verify if they are palindromes. However, this method is inefficient with a time complexity of O(n3), where n is the length of the string.

A more efficient method leverages the idea of expanding around potential centers. Since palindromes are mirrored around their center, we can iterate through the string and expand outward from each character (and between characters) to find all palindromic substrings. This approach reduces the time complexity to O(n2) and operates with O(1) extra space.

Ideal Algorithm and Data Structures

The Expand Around Center algorithm is ideal for this problem because it balances efficiency and simplicity. It doesn’t require additional data structures like dynamic programming tables, which consume O(n2) space. Instead, it uses simple variables to track the longest palindrome found during the expansion process.

This algorithm is effective on LeetCode because it meets the time and space efficiency requirements for the problem constraints. It successfully handles the maximum string length of 1000 characters without exceeding time limits or consuming excessive memory.

Understanding the Expand Around Center Algorithm

The core idea of the Expand Around Center algorithm is to consider each character in the string (and the space between characters) as potential centers of a palindrome. Since palindromes can be of odd or even length, we need to check for both cases:

  1. Odd-length palindromes: Centered around a single character.
  2. Even-length palindromes: Centered between two characters.

For each center, we expand outward (left and right) as long as the characters match. We keep track of the longest palindrome found during this process.

Detailed Solution Explanation

Let’s delve deeper into how the algorithm works. We start by initializing variables to keep track of the start and end indices of the longest palindromic substring found so far.

We iterate through each character in the string s. For each character at index i, we perform two expansions:

  1. Odd-length palindrome expansion:
    • We set both left and right pointers to i.
    • We expand outward while s[left] == s[right].
  2. Even-length palindrome expansion:
    • We set the left pointer to i and the right pointer to i + 1.
    • We expand outward while s[left] == s[right].

During each expansion, we check if the length of the palindrome found is greater than the maximum length recorded. If it is, we update the start and end indices accordingly.

The expansion continues until the characters at the left and right pointers are no longer equal or the pointers go out of bounds.

By the end of the iteration, the substring from start to end + 1 will be the longest palindromic substring in s.

Step-by-Step Solution for LeetCode 5 Problem

class Solution:

    def expand_from_center(self, s, left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1  # Move left pointer outward
            right += 1  # Move right pointer outward
        return right - left - 1  # Length of the palindrome

    def longestPalindrome(self, s: str) -> str:
        if not s or len(s) == 0:
            return ""

        start, end = 0, 0  # Initialize start and end indices of the longest palindrome

        for i in range(len(s)):
            len1 = self.expand_from_center(s, i, i)      # Odd-length palindromes
            len2 = self.expand_from_center(s, i, i + 1)  # Even-length palindromes
            max_len = max(len1, len2)

            if max_len > (end - start):
                # Update the start and end indices based on the new max length
                start = i - (max_len - 1) // 2
                end = i + max_len // 2

        return s[start:end + 1]

Explanation of the Code:

  • The longest_palindrome function initializes variables and iterates through the string.
  • For each character, it calls expand_from_center twice to handle both odd and even cases.
  • The expand_from_center function expands outward and returns the length of the palindrome found.
  • If a longer palindrome is found, the start and end indices are updated.
  • Finally, the function returns the longest palindromic substring using the updated indices.

Optimization Tips

  • Avoid Unnecessary Checks: By combining the odd and even length checks within the same loop, we minimize the number of iterations.
  • Efficient Index Management: Calculating the start and end indices using integer division ensures accurate substring extraction without extra computations.
  • In-place Expansion: The expand_from_center function operates without additional space, making the solution memory-efficient.

Conclusion

The Expand Around Center algorithm provides an elegant and efficient solution to LeetCode 5 problem: the Longest Palindromic Substring. By understanding the nature of palindromes and leveraging in-place expansion, we achieve a time complexity of O(n2) and a space complexity of O(1). This approach not only meets the problem’s requirements but also reinforces fundamental algorithmic concepts useful in string manipulation problems.

Happy Coding!

Understanding this algorithm not only solves this problem but also equips you with a valuable technique applicable to various other string and array challenges.


Looking for more LeetCode solutions? Stay tuned for upcoming guides on tackling other LeetCode challenges in Python. Whether you’re preparing for technical interviews or aiming to improve your coding skills, exploring a variety of problems will enhance your understanding and proficiency.

You can find this problem on LeedCode, click here.

Add comment

By Peter

About me

Hi, I’m Peter, a professional developer with over 25 years of experience. My journey with coding started when I was just a kid, exploring the world of programming and building my first projects out of pure curiosity and passion. Since then, I’ve turned this lifelong passion into a rewarding career, working on a wide range of projects, from small scripts to complex applications.

Now, I’m here to help others get started with coding through this blog. I know that learning to code can feel overwhelming at first, but I believe that with the right guidance, anyone can develop the skills they need to become a proficient programmer. My goal is to simplify the learning process and provide step-by-step resources that make coding accessible, fun, and practical for everyone.

Whether you’re just starting out or looking to sharpen your skills, I hope this blog serves as a valuable resource on your coding journey. Let’s dive into Python together!

Get in touch

Have any questions or feedback? Feel free to reach out—I’m always happy to help you on your coding journey!

Tags