Tutorialspoint
Problem
Solution
Submissions

Longest Palindromic Substring

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

Write a C program to find the longest palindromic substring in a given string. A palindrome is a string that reads the same forward and backward. If there are multiple palindromic substrings of the same maximum length, return any one of them.

Example 1
  • Input: s = "babad"
  • Output: "bab"
  • Explanation:
     Step 1: Check all possible substrings for palindrome property.
     Step 2: "bab" is a palindrome of length 3.
     Step 3: "aba" is also a palindrome of length 3.
     Step 4: Both are valid answers, so we return "bab".
Example 2
  • Input: s = "cbbd"
  • Output: "bb"
  • Explanation:
     Step 1: Check all possible substrings for palindrome property.
     Step 2: "bb" is a palindrome of length 2.
     Step 3: No longer palindrome exists in the string.
     Step 4: Therefore, "bb" is the longest palindromic substring.
Constraints
  • 1 ≤ s.length ≤ 1000
  • s consists of only lowercase English letters
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)
StringsHCL TechnologiesAirbnb
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.
  • For each character, consider it as the center of a palindrome.
  • Expand outward while characters match on both sides.
  • Handle both odd-length and even-length palindromes.
  • Keep track of the longest palindrome found so far.

Steps to solve by this approach:

 Step 1: Initialize variables to track the start position and maximum length of palindrome found.
 Step 2: For each character position, treat it as the center of an odd-length palindrome.
 Step 3: Expand outward from the center while characters on both sides match.
 Step 4: Update the longest palindrome if a longer one is found.
 Step 5: Repeat the process for even-length palindromes by considering adjacent characters as centers.
 Step 6: Extract and return the substring corresponding to the longest palindrome found.
 Step 7: Handle memory allocation for the result string properly.

Submitted Code :