Leftmost Longest Mirror-Reading Substring
StringsAuto-graded · 24 test casesLast updated
Find the longest contiguous substring that reads the same in both directions, returning the leftmost one on ties; tests center expansion or Manacher-style reasoning.
Longest Mirror-Reading Substring
You are given a string text. A substring is a block of consecutive characters, and it is a palindrome if it reads the same from left to right as from right to left.
Return the longest palindromic substring of text.
Tie-break rule
If several palindromic substrings share the maximum length, return the one that starts at the smallest index (the leftmost one). For example, in "babad" both "bab" and "aba" have length 3, so the answer is "bab".
Input
text: a non-empty string of ASCII letters and digits.
Output
- A string: the leftmost longest palindromic substring of
text.
Notes
- A single character is always a palindrome, so the result is never empty.
- Palindromes can have odd or even length. Make sure your approach handles both.
- Matching is case-sensitive, so
"A"and"a"are different characters.
Constraints
1 <= len(text) <= 2000textcontains only ASCII letters and digits.- Exactly one string is expected as output, following the tie-break rule above.
Examples
Example 1
Input: leftmost_longest_palindrome('babad')
Output: 'bab'
Example 2
Input: leftmost_longest_palindrome('cbbd')
Output: 'bb'
Example 3
Input: leftmost_longest_palindrome('a')
Output: 'a'
Example 4
Input: leftmost_longest_palindrome('ac')
Output: 'a'
Hints
Hint 1
Every palindrome mirrors around a center. For a string of length n there are 2n - 1 centers: n characters (odd length) and n - 1 gaps between neighbors (even length).
Hint 2
From each center, move two pointers outward while the characters match. Track the best length seen so far, and only replace the best when a candidate is strictly longer so the leftmost one is kept.
Hint 3
For the start index, a palindrome of length L found by expanding from left index l and right index r (before stepping out) starts at l + 1 after the loop ends at the first mismatch. Check your arithmetic on 'cbbd'. For a linear-time version, look into Manacher's algorithm.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every palindrome is symmetric around a center. A string of length n has 2n - 1 centers: n characters (odd-length palindromes) and n - 1 gaps (even-length palindromes).
The simplest solution expands outward from each center while the two characters match. That takes O(n^2) time and O(1) extra space, which is fine for n <= 2000. The reference solution uses Manacher's algorithm, which brings the time down to O(n).
Unifying odd and even lengths
Build a new string t by putting # between all characters and at both ends, then adding two distinct sentinels ^ and $ at the outer ends:
text = "cbbd" -> t = "^#c#b#b#d#$"
Every palindrome in t is now odd-length and centered at a single index. Even-length palindromes of text are centered on a #. The sentinels differ from each other and from all input characters, so the expansion loop stops at the boundaries without any index checks.
Let radius[i] be how far the palindrome centered at t[i] extends in each direction. This value equals the length of the corresponding palindrome in text, and that palindrome starts at index (i - radius[i]) // 2 in text.
Reusing work with mirroring
Keep track of the palindrome that reaches furthest right, with center center and right edge right. For a new index i < right, its mirror 2*center - i lies inside that big palindrome, and the surroundings of i look the same as those of the mirror up to the window edge. So radius[i] is at least min(right - i, radius[mirror]). Start from that value and keep expanding until a mismatch.
Why it is correct
- The
#characters pair only with other#characters at equal distances, so they never create false matches, and each palindrome intmaps exactly to one intext. - The mirror value is only a lower bound, and the
whileloop always expands to the first mismatch, so eachradius[i]is exact. - Centers are visited left to right. For equal lengths the start index
(i - length) // 2grows withi, and we only update on a strictly larger length, so the leftmost longest palindrome is kept.
Complexity
- Time: O(n). Each successful expansion step moves
rightfurther right, andrightnever decreases and is bounded by2n + 3. - Space: O(n) for the transformed string and the radius array.
Edge cases
- A single character returns itself.
- With no repeated neighbors (such as
"ac"), the first character is returned because of the tie-break. - Even-length answers (such as
"cbbd"giving"bb") are handled by centers on#. - If the whole string is a palindrome, the whole string is returned.
Reference solution
def leftmost_longest_palindrome(text: str) -> str:
# Manacher's algorithm on a transformed string. Centers are scanned from
# left to right and the best answer is replaced only on a strictly longer
# length, so the leftmost longest palindrome wins.
t = '^#' + '#'.join(text) + '#$'
n = len(t)
radius = [0] * n
center = right = 0
best_len = 0
best_start = 0
for i in range(1, n - 1):
mirror = 2 * center - i
if i < right:
radius[i] = min(right - i, radius[mirror])
while t[i + 1 + radius[i]] == t[i - 1 - radius[i]]:
radius[i] += 1
if i + radius[i] > right:
center = i
right = i + radius[i]
length = radius[i]
start = (i - length) // 2
if length > best_len:
best_len = length
best_start = start
return text[best_start:best_start + best_len]