KatInterview

Earliest Longest Mirror Segment in a String

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstringspalindromeexpand-around-center

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