Good evening! Here's our prompt for today.
We have a string str
like the following:
JAVASCRIPT
1const str = "bubble";
Find a way to convert it to a palindrome by inserting characters in front of it. Recall that a palindrome
is defined as "a word, phrase, or sequence that reads the same backward as forward".

What's the shortest palindrome that can be returned? For example, the following above string should return:
JAVASCRIPT
1shortestPalindrome("bubble")
2// "elbbubble"
Constraints
- Length of the given string <=
1000
- The string can contain any ASCII letters
- Expected time complexity :
O(n)
- Expected space complexity :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
24
def shortestPalindrome(s):
# fill in
return ""
​
​
import unittest
​
​
class Test(unittest.TestCase):
def test_1(self):
assert shortestPalindrome("bubble") == "elbbubble"
print("PASSED: `shortestPalindrome('bubble')` should return `'elbbubble'`")
​
def test_2(self):
assert shortestPalindrome("dasndsadmx") == "xmdasdnsadasndsadmx"
print(
"PASSED: `shortestPalindrome('dasndsadmx')` should return `'xmdasdnsadasndsadmx'`"
)
​
​
if __name__ == "__main__":
unittest.main(verbosity=2)
print("Nice job, 2/2 tests passed!")
​
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.