# 5. Longest Palindromic Substring

```jsx
/**
 * @param {string} s
 * @return {string}
 */
 /**
 time: O(n^3)
 space: O(n)
*/
var longestPalindrome = function(s) {
    let max = s[0];

    for (let i = 0; i < s.length; i++) {
        for (let j = i; j < s.length; j++) {
            if (isPalindrome(s, i, j)) {
                if (j - i + 1 >= max.length) {
                    max = s.substring(i, j + 1);
                }
            }
        }
    }

    return max;
};

function isPalindrome(str, s, e) {
    while (s <= e) {
        if (str[s] !== str[e]) {
            return false;
        }
        s++;
        e--;
    }

    return true;
}
```

```jsx
/**
time: O(n^2)
space: O(n)
 */
var longestPalindrome = function(s) {
    let max = [0, 1];

    for (let i = 0; i < s.length - 1; i++) {
        const odd = getLongest(s, i, i);
        const even = getLongest(s, i, i + 1);
        
        // find longest btw odd and even
        let current = even;
        if (odd[1] - odd[0] >= even[1] - even[0]) {
            current = odd;
        }

        // find longest btw current and current max
        if (current[1] - current[0] > max[1] - max[0]) {
            max = current;
        }
    }
    
    return s.slice(max[0], max[1]);
};

function getLongest(str, s, e) {
    while (s >= 0 && e < str.length) {
        if (str[s] !== str[e]) {
            break;
        }
        s--;
        e++;
    }

    return [s + 1, e];
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/string/5.-longest-palindromic-substring.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
