ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Longest Palindromic Substring

Groovy

Goal -- WPM

Ready
Exercise Algorithm Area
1class LongestPalindromeFinder {
2
3/**
4* Finds the longest palindromic substring within a given string.
5* This method uses the 'Expand Around Center' approach.
6*
7* @param s The input string.
8* @return The longest palindromic substring.
9* @throws IllegalArgumentException if the input string is null or empty.
10*/
11public String longestPalindrome(String s) {
12if (s == null || s.length() < 1) {
13throw new IllegalArgumentException("Input string cannot be null or empty.");
14}
15
16int start = 0;
17int end = 0;
18
19// Iterate through each character as a potential center of a palindrome.
20for (int i = 0; i < s.length(); i++) {
21// Case 1: Palindrome centered at a single character (e.g., "aba")
22int len1 = expandAroundCenter(s, i, i);
23// Case 2: Palindrome centered between two characters (e.g., "abba")
24int len2 = expandAroundCenter(s, i, i + 1);
25
26// Get the maximum length from the two cases.
27int len = Math.max(len1, len2);
28
29// If the current palindrome is longer than the longest found so far,
30// update the start and end indices.
31if (len > end - start) {
32// For odd length palindromes (len1), the center is i.
33// For even length palindromes (len2), the center is between i and i+1.
34// The formula (i - (len - 1) / 2) correctly calculates the start index
35// for both odd and even length palindromes.
36start = i - (len - 1) / 2;
37end = i + len / 2;
38}
39}
40
41// Extract the longest palindromic substring using the final start and end indices.
42// The substring method's end index is exclusive, so we add 1.
43return s.substring(start, end + 1);
44}
45
46/**
47* Expands around a given center (or pair of centers) to find the length of the palindrome.
48*
49* @param s The input string.
50* @param left The left index of the center.
51* @param right The right index of the center.
52* @return The length of the palindrome found expanding from the center(s).
53*/
54private int expandAroundCenter(String s, int left, int right) {
55int L = left;
56int R = right;
57
58// Expand as long as the characters match and we are within string bounds.
59while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
60L--;
61R++;
62}
63
64// The length of the palindrome is R - L - 1.
65// For example, if L becomes -1 and R becomes 3 for "aba", length is 3 - (-1) - 1 = 3.
66// If L becomes 0 and R becomes 1 for "aa", length is 1 - 0 - 1 = 0 (incorrect, should be 2).
67// The correct calculation is R - L - 1. For "aa", L=-1, R=2, length = 2 - (-1) - 1 = 2.
68// For "aba", L=0, R=2, length = 2 - 0 - 1 = 1 (incorrect, should be 3).
69// Let's re-evaluate. When loop breaks, L is one step too far left, R is one step too far right.
70// The valid palindrome indices are L+1 to R-1.
71// Length = (R-1) - (L+1) + 1 = R - 1 - L - 1 + 1 = R - L - 1.
72// Example "aba", i=1. len1=expand(s,1,1). L=1,R=1. s[1]==s[1]. L=0,R=2. s[0]==s[2]. L=-1,R=3. Loop ends. R-L-1 = 3 - (-1) - 1 = 3.
73// Example "abba", i=1. len2=expand(s,1,2). L=1,R=2. s[1]==s[2]. L=0,R=3. s[0]==s[3]. L=-1,R=4. Loop ends. R-L-1 = 4 - (-1) - 1 = 4.
74return R - L - 1;
75}
76}
Algorithm description viewbox

Longest Palindromic Substring

Algorithm description:

This program finds the longest palindromic substring within a given string using the 'Expand Around Center' approach. A palindrome is a sequence that reads the same backward as forward. This algorithm efficiently checks all possible palindromic substrings by considering each character and the space between characters as potential centers. A practical application is in text processing, search engines, or bioinformatics where identifying palindromic sequences is crucial.

Algorithm explanation:

The 'Expand Around Center' algorithm has a time complexity of O(n^2), where n is the length of the string. This is because there are 2n-1 possible centers (n characters and n-1 spaces between characters), and for each center, we might expand up to n/2 characters in both directions. The space complexity is O(1) as we only use a few variables to store indices and lengths. The algorithm iterates through all possible centers. For each center, it expands outwards as long as the characters match and stay within the string boundaries. It keeps track of the longest palindrome found so far by updating the start and end indices. Edge cases include null or empty input strings, and strings with only one character. The correctness is guaranteed by exhaustively checking all potential palindromic centers and their maximum possible expansions.

Pseudocode:

function longestPalindrome(string s):
  if s is null or empty:
    throw error

  start = 0
  end = 0

  for i from 0 to length(s) - 1:
    // Expand around single character center
    len1 = expandAroundCenter(s, i, i)
    // Expand around center between two characters
    len2 = expandAroundCenter(s, i, i + 1)

    maxLength = max(len1, len2)

    // If current palindrome is longer than the longest found so far
    if maxLength > (end - start):
      start = i - (maxLength - 1) / 2
      end = i + maxLength / 2

  return substring of s from start to end (inclusive)

function expandAroundCenter(string s, left, right):
  L = left
  R = right
  while L >= 0 and R < length(s) and s[L] == s[R]:
    L = L - 1
    R = R + 1
  // Length is R - L - 1
  return R - L - 1