Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    The longest palindrome inside a text

    MediumAbout 25 minFull AccessLearn it: Palindromes in C#: Longest Palindromic Substring, Counting Palindromes and Fewest Cuts

    The task

    A text-analysis tool highlights the longest stretch of a string that reads the same forwards and backwards.

    Complete LongestPalindrome(string s). Return the longest contiguous part of s that reads the same in both directions; matching is case-sensitive. When several have the longest length, return the one that starts first. An empty string gives an empty string. The string is never null.

    Signature

    public static string LongestPalindrome(string s)

    Examples

    • "abba" → "abba". An even-length palindrome has no middle letter.
    • "abcbadefed" → "abcba". "defed" is just as long, but "abcba" starts first.

    Limits: Up to 8,001 characters.

    The tests check: an empty string, one and two letters, even and odd lengths, a palindrome at the start or in the middle, no repeated letter, the earlier of two equal lengths, letter case, and two 8,001-letter texts in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public static class Solution
      {
          // The longest palindromic substring; the earliest one on a tie.
          public static string LongestPalindrome(string s)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.