Tutorialspoint
Problem
Solution
Submissions

Longest Palindromic Substring

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to find the longest palindromic substring in a given string. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. For example, "racecar" is a palindrome because it reads the same in both directions.

Example 1
  • Input: s = "babad"
  • Output: "bab"
  • Explanation:
    • The string "babad" contains multiple palindromic substrings.
    • We can find "bab" starting at index 0, which has length 3.
    • We can also find "aba" starting at index 1, which also has length 3.
    • Both are valid answers since they have the same maximum length.
Example 2
  • Input: s = "cbbd"
  • Output: "bb"
  • Explanation:
    • The string "cbbd" is analyzed for palindromic substrings.
    • Individual characters 'c', 'b', 'b', 'd' are palindromes of length 1.
    • The substring "bb" at indices 1-2 is a palindrome of length 2.
    • "bb" is the longest palindromic substring in this case.
Constraints
  • 1 ≤ s.length ≤ 1000
  • s consists of only lowercase English letters
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)
StringsWalmartArctwist
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

  • Use the "expand around centers" approach to check for palindromes
  • For each character, treat it as a potential center of a palindrome
  • Expand outward from each center while characters match
  • Handle both odd-length and even-length palindromes separately
  • Keep track of the longest palindrome found so far

Steps to solve by this approach:

 Step 1: Initialize variables to track the starting position and maximum length of the longest palindrome found.

 Step 2: Create a helper function that expands around a given center to find palindromes.
 Step 3: For each position in the string, use it as a center for odd-length palindromes.
 Step 4: For each position in the string, use it and the next position as centers for even-length palindromes.
 Step 5: In the expand function, move outward while characters match and update the longest palindrome if a longer one is found.
 Step 6: Continue until all possible centers have been checked.
 Step 7: Return the substring using the recorded start position and maximum length.

Submitted Code :