714129. Special Palindrome Substrings

Medium

Special Palindrome Substrings

Summary

Given a string, find all special palindrome substrings. A substring is considered special if it is a palindrome and its first and last characters are the same.

This problem involves manipulating strings to extract special palindromes. We'll use dynamic programming to solve this problem efficiently.

Detailed Explanation

To solve this problem, we'll follow these steps:

  1. Initialize an empty list palindromes to store all special palindrome substrings.
  2. Iterate through the string from left to right using a variable i.
  3. For each character at index i, check if it's the same as the character at index n-i-1. If they're not equal, skip this substring and move on to the next one.
  4. While the characters at indices i and n-i-1 are equal, increment i until they're no longer equal or we reach the middle of the string (when i == n/2).
  5. The substring from index i to n-i-1 is a special palindrome. Add it to the palindromes list.
  6. Return the palindromes list.

Here's an example: given the string "abccba", we'd find substrings like "b" and "abcba" (which is itself) as special palindromes.

Time complexity: O(n^2), where n is the length of the input string. We're doing a nested loop, iterating through the string twice. Space complexity: O(n), as we need to store all special palindrome substrings in the palindromes list.

Optimized Solutions

Java

View on GeeksforGeeks
public List<String> findSpecialPalindromeSubstrings(String s) {
    int n = s.length();
    List<String> palindromes = new ArrayList<>();
    
    for (int i = 0; i < n; i++) {
        int left = i, right = n - i - 1;
        
        while (left <= right && s.charAt(left) == s.charAt(right)) {
            if (left == right) {
                palindromes.add(String.valueOf(s.charAt(left)));
            } else {
                palindromes.add(s.substring(left, right + 1));
            }
            left++; right--;
        }
    }
    
    return palindromes;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.