KatInterview

Leftmost Longest Mirror-Reading Substring

StringsAuto-graded · 24 test cases
MediumAuto-gradedStringsstringspalindrometwo-pointers

Last 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) <= 2000
  • text contains 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.