Skip to the content

The palindrome inscription

Problem

The scribes of Ur-Anat carved their walls with letters run together, no spaces, and they taught that the sacred part was the chunk that reads the same from left to right as from right to left.

You get the inscription, a text of lowercase letters with no spaces (it may be empty). Return, as a text, the longest chunk that reads the same backwards. A chunk is letters in a row, with none skipped. It can have even length, like "abba", or odd, like "aba", and a single letter already reads the same backwards. If two chunks tie in length, return the one that starts first. With an empty text, return "".

In "tabacdc", "aba" and "cdc" read the same backwards, both of length 3, and none is longer. They tie, and "aba" starts first: you return "aba".

Examples

  • The example

    "tabacdc" → "aba"

  • Even length

    "xabbay" → "abba"

  • The whole word

    "racecar" → "racecar"

  • None is longer than one letter

    "abc" → "a"

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def longest_palindrome(text):
    pass

JavaScript

function longestPalindrome(text) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →