Earliest Longest Mirror Segment in a String
StringsAuto-graded · 23 test casesLast updated
Find the longest contiguous segment of a string that reads identically in both directions, preferring the leftmost one on ties and returning an empty string for empty input.
Longest Mirror Segment
You are given a string text. A mirror segment is a contiguous block of characters that reads exactly the same from left to right as from right to left.
Return the longest mirror segment contained in text.
Rules
- If several mirror segments share the greatest length, return the one whose starting index is smallest.
- Character comparison is case-sensitive, and digits and symbols are treated like any other character.
- If
textis empty, return the empty string"". - A single character is itself a mirror segment, so any non-empty string has an answer of length at least 1.
Input
text: a string of printable ASCII characters.
Output
- A string: the longest mirror segment, chosen according to the tie-break rule above.
Constraints
0 <= len(text) <= 1000textcontains English letters, digits, and common symbols.
Examples
Example 1
Input: longest_mirror_segment('babad')
Output: 'bab'
Example 2
Input: longest_mirror_segment('cbbd')
Output: 'bb'
Example 3
Input: longest_mirror_segment('')
Output: ''
Hints
Hint 1
Every mirror segment has a center: either a single character (odd length) or the gap between two adjacent characters (even length). There are 2n - 1 centers in total.
Hint 2
From each center, move two pointers outward while the characters they point to are equal. Remember to handle both the odd and the even center types.
Hint 3
To satisfy the tie-break, only replace your current best when a candidate is strictly longer, and scan centers so that earlier starting positions are considered first (or compare start indices explicitly on equal lengths).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every palindromic segment is symmetric around a center. For odd lengths the center is a character, and for even lengths it is the gap between two neighbouring characters, giving 2n - 1 centers overall.
For each center, place two pointers (l, r) and move them outward as long as they stay inside the string and the characters at both pointers are equal. When the loop stops, the segment text[l+1 .. r-1] is the longest mirror segment around that center.
We keep track of the best (start, length) seen so far. A candidate replaces the current best if it is strictly longer, or if it has the same length but a smaller start index. The explicit start comparison matters because odd and even centers are interleaved, so a segment found later is not guaranteed to start later.
If the string is empty, we return "" immediately. Otherwise the initial best is the first character, which is correct when no longer mirror segment exists (for example "abcdef" gives "a").
Why it is correct
- Every mirror segment has exactly one center, and expanding from that center finds the maximal segment around it, so the longest overall segment is among the candidates considered.
- The comparison rule (longer wins; on equal length, smaller start wins) implements the required tie-break exactly, regardless of the order in which centers are processed.
- Both odd and even centers are tried, so cases such as
"cbbd"are handled.
Complexity
- Time: O(n^2) in the worst case (for example a string of identical characters), which is fine for
n <= 1000. - Space: O(1) extra, apart from the returned slice.
(Manacher's algorithm can reduce the time to O(n), but it is not required for these constraints.)
Reference solution
def longest_mirror_segment(text: str) -> str:
n = len(text)
if n == 0:
return ""
best_start = 0
best_length = 1
def consider(l, r):
# Expand outward from the given center while characters match.
nonlocal best_start, best_length
while l >= 0 and r < n and text[l] == text[r]:
l -= 1
r += 1
start = l + 1
length = r - l - 1
if length > best_length or (length == best_length and start < best_start):
best_start = start
best_length = length
for i in range(n):
consider(i, i) # odd-length centers
consider(i, i + 1) # even-length centers
return text[best_start:best_start + best_length]