Tutorialspoint
Problem
Solution
Submissions

Longest Palindromic Substring

Certification: Advanced Level Accuracy: 75% Submissions: 16 Points: 15

Write a Python function that finds the longest palindromic substring in a given string. A palindrome is a string that reads the same backward as forward.

Example 1
  • Input: "babad"
  • Output: "bab" (Note: "aba" is also a valid answer)
  • Explanation:
    • Step 1: Take the input string "babad".
    • Step 2: Identify all palindromic substrings.
    • Step 3: Find the longest ones, which are "bab" and "aba".
    • Step 4: Return either "bab" or "aba" as they're the same length.
Example 2
  • Input: "cbbd"
  • Output: "bb"
  • Explanation:
    • Step 1: Take the input string "cbbd".
    • Step 2: Identify all palindromic substrings.
    • Step 3: Find the longest one, which is "bb".
    • Step 4: Return "bb" as the result.
Constraints
  • 1 ≤ string length ≤ 1000
  • String contains only lowercase English letters
  • Time Complexity: O(n²), where n is the length of the string
  • Space Complexity: O(1)
Dynamic Programming AlgorithmsAmazonTutorialspoint
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Expand around center approach: check palindromes by expanding from each position
  • Dynamic programming: build a table dp[i][j] indicating if s[i:j+1] is a palindrome
  • Manacher's algorithm for O(n) time complexity but more complex implementation
  • Handle even and odd length palindromes separately

Steps to solve by this approach:

 Step 1: For each character in the string, consider it as a potential center of a palindrome.

 Step 2: Expand around the center for both odd and even length palindromes.
 Step 3: For odd length, expand around single character (i,i).
 Step 4: For even length, expand around adjacent characters (i,i+1).
 Step 5: Keep track of the start position and maximum length of palindromes found.
 Step 6: Return the substring from start to start+max_length.

Submitted Code :