# 214 Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

For example:

Given`"aacecaaa"`, return`"aaacecaaa"`.

Given`"abcd"`, return`"dcbabcd"`.

Brute Force idea: check for matching substrings

```
Ex1:

abcd
dcba
abc
cba
ab
ba
a
a

Ex2:
adcbabcd
aacecaaa
aaacecaa
aacecaa
aacecaa
```

```cpp
string shortestPalindrome(string s) {
    string r = s;
    reverse(r.begin(), r.end());

    const size_t size = s.length();
    int i = 0;
    for (i; i < size; i++) {
        if (s.substr(0, size - i) == r.substr(i))
            break;
    }

    return r.substr(0, i) + s;
}


int main()
{
    cout << shortestPalindrome("abcd") << endl;
    cout << shortestPalindrome("aacecaaa") << endl;
}
```


---

# 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://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/214-shortest-palindrome.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.
