Taro Logo

Longest Palindromic Substring

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+51
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
3.4K views
Topics:
StringsDynamic Programming

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

Example 1:

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

Example 2:

Input: s = "cbbd"
Output: "bb"

Constraints:

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input string `s`, and are we guaranteed that `s` only contains standard ASCII or alphanumeric characters, or should we account for Unicode/surrogate pairs?
  2. If the input string is empty or has a length of zero, what should be returned—an empty string or a specific null-like value?
  3. How should ties be handled if there are multiple palindromic substrings of the exact same maximum length (e.g., returning the first one that appears, or does any valid one suffice)?
  4. Can I assume that the input string will always fit entirely in memory, or could it be extremely large where streaming or space optimization becomes critical?
  5. Is case sensitivity enforced, meaning that characters like 'A' and 'a' should be treated as distinct, or should palindromic checks be case-insensitive?

Brute Force Solution

Approach

The brute force approach to finding the longest palindromic part of a text is to systematically check every single possible continuous segment of the text to see if it reads the same forwards and backwards. By doing this exhaustive search, we are guaranteed to find the longest one because no option is left untested.

Here's how the algorithm would work step-by-step:

  1. Look at the original text and identify every possible smaller piece that you can form by taking a continuous chunk of letters.
  2. For every single one of these chunks, take the letters and compare the way they read forwards against the way they read backwards from the end to the start.
  3. Determine whether the chunk reads the exact same way in both directions, which means it is a palindrome.
  4. Keep a mental note of all the chunks that successfully pass this test and qualify as a palindrome.
  5. Compare the sizes of all the successful palindromes you found during your check.
  6. Select the largest one among them as your final answer.

Code Implementation

def longest_palindrome_brute_force(text_string):
    longest_palindrome_found = ""

    # Generate every possible continuous chunk to ensure no potential palindrome is missed
    for start_index in range(len(text_string)):
        for end_index in range(start_index + 1, len(text_string) + 1):
            current_chunk = text_string[start_index:end_index]

            # Verify if the chunk reads the same forwards and backwards to qualify as valid
            if current_chunk == current_chunk[::-1]:

                # Compare current palindrome length against the maximum found so far to track the best
                if len(current_chunk) > len(longest_palindrome_found):
                    longest_palindrome_found = current_chunk

    return longest_palindrome_found

Big(O) Analysis

Time Complexity
O(n³) – To find the longest palindromic substring using the brute force approach, we first use nested loops to generate every possible continuous chunk of the text, which takes O(n²) starting and ending positions. For each of these chunks, we must iterate across its length to check if it reads the same forwards and backwards, adding another factor of proportional work up to n. This leads to approximately n³ over 6 total operations when considering all possible substring lengths and positions, which simplifies to a cubic time complexity of O(n³).
Space Complexity
O(1) – The brute force approach as described evaluates every continuous segment directly within the original text without gathering chunks into a temporary list or storing intermediate results. The space usage is limited to a few primitive tracking variables for the loop indices and the boundaries of the largest palindrome found so far. Consequently, the extra memory required remains constant and does not scale as the input text length N grows.

Optimal Solution

Approach

Instead of checking every single possible piece of text from the beginning, the optimal approach treats every letter and every space between letters as the exact middle of a potential mirror image. It then checks outward from that middle as far as possible to see how large of a symmetrical piece can be formed.

Here's how the algorithm would work step-by-step:

  1. Look at the entire text from left to right, focusing on one spot at a time.
  2. Treat the current spot as the very center of a potential mirror image.
  3. Expand outward to the left and right at the same time, checking if the matching outer letters are identical.
  4. Keep expanding outward step by step as long as the matching outer letters continue to be identical.
  5. Stop expanding the moment the matching outer letters stop matching or you run out of text.
  6. Remember the size of the symmetrical piece you just found if it is bigger than your previous record.
  7. Consider another type of center located right between two adjacent letters, and repeat the outward expansion process.
  8. After testing every possible single-letter center and every between-letter center, the biggest symmetrical piece found during the process is your final answer.

Code Implementation

class Solution:
    def longestPalindrome(self, input_string: str) -> str:
        if not input_string:
            return ""

        max_start_index = 0
        max_length_found = 0

        def expand_around_center(left_pointer: int, right_pointer: int) -> int:
            while left_pointer >= 0 and right_pointer < len(input_string) and input_string[left_pointer] == input_string[right_pointer]:
                left_pointer -= 1
                right_pointer += 1
            return right_pointer - left_pointer - 1

        # We check every position as a potential single center or dual center to find all palindromes.
        for center_index in range(len(input_string)):
            odd_palindrome_length = expand_around_center(center_index, center_index)
            even_palindrome_length = expand_around_center(center_index, center_index + 1)

            current_max_length = max(odd_palindrome_length, even_palindrome_length)

            # We update our global bounds only when a strictly larger palindrome is discovered.
            if current_max_length > max_length_found:
                max_length_found = current_max_length
                max_start_index = center_index - (current_max_length - 1) // 2

        # Slicing from the recorded start index to the maximum length yields the longest palindrome substring.
        return input_string[max_start_index:max_start_index + max_length_found]

Big(O) Analysis

Time Complexity
O(n²) – For each of the n characters in the text, we treat it as a center and potentially also consider the center between it and the next character. From each of these up to 2n-1 possible centers, we expand outward in both directions to check matching letters, which takes up to n steps in the worst-case scenario. This combination of iterating through all centers and expanding outward leads to roughly n * n operations. Simplifying this expression by dropping constants gives a final Big O time complexity of O(n²).
Space Complexity
O(1) – The algorithm only requires a few primitive integer variables, such as pointers for the current center and expansion boundaries, and trackers for the longest palindrome found so far. No auxiliary data structures like temporary arrays, lists, or hash maps are created regardless of the input string length N. Furthermore, the expansion process is handled iteratively without recursion, meaning the call stack does not grow. As the input size N increases, the extra memory required remains constant.

Edge Cases

Empty string or string with a length of zero
How to Handle:
Return an empty string immediately since no valid palindromic substring can exist.
String with a single character
How to Handle:
Return the character itself as any single-character string is trivially a palindrome of length one.
String with all identical characters
How to Handle:
Expand around center or dynamic programming approach correctly identifies the entire string as the longest palindrome.
String with no palindromes longer than one character
How to Handle:
Return any single character from the string as the default longest palindrome of length one.
String with multiple palindromes of the exact same maximum length
How to Handle:
Maintain tracking variables to capture and return the first or any valid maximum-length palindromic substring encountered.
Maximum-sized inputs near the upper constraint limit
How to Handle:
Use the expand-around-center approach with O(n^2) time complexity and O(1) space complexity to prevent memory limit and timeout issues.
Inputs with mixed case sensitivity or special unicode characters
How to Handle:
Treat characters strictly by their exact ASCII or Unicode values unless a case-insensitive preprocessing step is explicitly required.
Even-length palindromes versus odd-length palindromes
How to Handle:
Check both single-character centers and between-character centers during expansion to correctly catch both types of palindromes.
0/75 completed