Main content
Course: Computer science theory > Unit 1
Lesson 6: Recursive algorithms- Recursion
- The factorial function
- Challenge: Iterative factorial
- Recursive factorial
- Challenge: Recursive factorial
- Properties of recursive algorithms
- Using recursion to determine whether a word is a palindrome
- Challenge: is a string a palindrome?
- Computing powers of a number
- Challenge: Recursive powers
- Multiple recursion with the Sierpinski gasket
- Improving efficiency of recursive functions
- Project: Recursive art
© 2024 Khan AcademyTerms of usePrivacy PolicyCookie Notice
Using recursion to determine whether a word is a palindrome
A palindrome is a word that is spelled the same forward and backward. For example, rotor is a palindrome, but motor is not.
How can you use recursion to determine whether a word is a palindrome? Let's start by understanding what's a base case. Consider the word a. It's a palindrome. In fact, we don't have to think of palindromes as actual words in the English language (or whatever language you'd like to consider). We can think of a palindrome as just any sequence of letters that reads the same forward and backward, such as xyzyzyx. We call a sequence of letters a string. So we can say that any string containing just one letter is by default a palindrome. Now, a string can contain no letters; we call a string of zero letters an empty string. An empty string is also a palindrome, since it "reads" the same forward and backward. So now let's say that any string containing at most one letter is a palindrome. That's our base case: a string with exactly zero letters or one letter is a palindrome.
What if the string contains two or more letters? Here's where we'll have our recursive case. Consider the palindrome rotor. Its first and last letters are the same, and this trait must hold for any palindrome. On the other hand, if the first and last letters are not the same, as in motor, then the string cannot possibly be a palindrome. So now we have a way to declare that a string is not a palindrome: when its first and last letters are different. We can think of this situation as another base case, since we have the answer immediately. Going back to when the first and last letters are the same, what does that tell us? The string might be a palindrome. Then again, it might not be. In the string rater, the first and last letters are the same, but the string is not a palindrome. Suppose we strip off the first and last letters, leaving the string ate. Then the first and last letters of this remaining string are not the same, and so we know that rater is not a palindrome.
So here's how we can recursively determine whether a string is a palindrome. If the first and last letters differ, then declare that the string is not a palindrome. Otherwise, strip off the first and last letters, and determine whether the string that remains—the subproblem—is a palindrome. Declare the answer for the shorter string to be the answer for the original string. Once you get down to a string with no letters or just one letter, declare it to be a palindrome. Here's a visualization of that for two words that we discussed:
How would we describe that in pseudocode?
- If the string is made of no letters or just one letter, then it is a palindrome.
- Otherwise, compare the first and last letters of the string.
- If the first and last letters differ, then the string is not a palindrome.
- Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string.
This content is a collaboration of Dartmouth Computer Science professors Thomas Cormen and Devin Balkcom, plus the Khan Academy computing curriculum team. The content is licensed CC-BY-NC-SA.
Want to join the conversation?
- Can someone explain how to calculate the time complexity of the "Challenge: is a string a palindrome?". I'm thinking it would be Theta(n) but can someone please verify?(9 votes)
- Assuming worst case scenario (the string is a palindrome)
Cost of checking string:
- cost of: final check for 0 or 1 length string: c1 ( a constant)
- for every 2 additional letters:
cost of: check for length + checking first and last character match: c2
So the cost is: c1+ n/2*c2 or Theta(n)(8 votes)
- How can no words or no letters be a palindrome?(5 votes)
- An empty string reads the same forwards and backwards.(6 votes)
- Can someone explain pseudocode further?(3 votes)
- Hello Anna. The pseudocode is very detailed, there is probably no way to explain it further. Try to look at my implementation in Java and compare it with the pseudocode. If you still won't understand anything, feel free to ask. :)
private boolean isPalindrom(String str) {
if (str.length() == 0 || str.length() == 1){
return true;
} else {
if (str.charAt(0) != str.charAt(str.length() - 1)){
return false;
} else {
return isPalindrom(str.substring(1, str.length()-1));
}
}
}(8 votes)
- // base case #2
if(firstCharacter===lastCharacter) {
str.slice(firstCharacter, lastCharacter);
}
If the first and last characters are the same, slice them out. What am I missing?(3 votes)- The instructions say base case 2 is:
"If the first and last characters of the string are different"(5 votes)
- Can you please tell me in which language the challenge is written?(2 votes)
- its java script.(3 votes)
- I'm stuck on step 3. What should I do? Here is my code:
// Returns the first character of the string str
var firstCharacter = function(str) {
return str.slice(0, 1);
};
// Returns the last character of a string str
var lastCharacter = function(str) {
return str.slice(-1);
};
// Returns the string that results from removing the first
// and last characters from str
var middleCharacters = function(str) {
return str.slice(1, -1);
};
var isPalindrome = function(str) {
// base case #1
if (str.length <= 1) {
return true;
}
// base case #2
if (firstCharacter(str) !== lastCharacter(str)) {
return false;
}
// recursive case
return true;
};
var checkPalindrome = function(str) {
println("Is this word a palindrome? " + str);
println(isPalindrome(str));
};
checkPalindrome("a");
Program.assertEqual(isPalindrome("a"), true);
checkPalindrome("motor");
Program.assertEqual(isPalindrome("motor"), false);
checkPalindrome("rotor");
//Program.assertEqual(isPalindrome("rotor"), true);(2 votes)- seriously, how did you get it??(3 votes)
How do i find the strings
length?(1 vote)- check it's length property
e.g if s is the string "Hello" then s.length is 5(4 votes)
- So, I'm not sure what to do on step three of the "Challenge: Is a string a palindrome?", doing what the hint told me to do along with the instructions, but nothing worked?
After doing
//base #2 (the second step
I've done the
//recursive case
return true;
};
But the test didn't run right it seems..? But I didn't get an "hm, did you check to see the assertion is passing?" or something like that..(2 votes)- I'm assuming you've passed the base case #2 step and are working on step #3.
If you're doing the recursive case, it should be recursive i.e. theisPalindrome
function should call itself there. The instructions also say to make use of themiddleCharacters
function.(2 votes)
- Finally, write the recursive case.
Use the provided function middleCharacters to remove the first and last characters from the string.
Check that the console output from the checkPalindrome function is correct.
Once implemented, uncomment the Program.assertEqual() for isPalindrome("rotor") at the bottom to verify that the test assertion passes.(2 votes) - Why use splice instead of passing the index?(2 votes)