#3844

Longest Almost-Palindromic Substring

Medium
Two PointersStringDynamic ProgrammingTwo PointersDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Use a two-pointer approach to expand around potential centers of palindromes, checking if removing one character can yield a palindrome.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through each character as a center (for odd and even lengths).
  2. 2Step 2: Expand outwards while characters match, allowing one mismatch.
  3. 3Step 3: Track the maximum length of valid almost-palindromic substrings.
solution.py19 lines
1def longest_almost_palindromic_substring(s):
2    def expand_around_center(left, right):
3        count = 0
4        while left >= 0 and right < len(s):
5            if s[left] == s[right]:
6                left -= 1
7                right += 1
8            else:
9                count += 1
10                if count > 1:
11                    break
12                left -= 1
13                right += 1
14        return right - left - 1
15
16    max_len = 0
17    for i in range(len(s)):
18        max_len = max(max_len, expand_around_center(i, i), expand_around_center(i, i + 1))
19    return max_len

Complexity note: The two-pointer technique allows us to check potential palindromic centers in linear time.

  • 1Identify centers for potential palindromes.
  • 2Allow one mismatch while expanding.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.