Main content

## Computer science

### 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

© 2023 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?(8 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)

- Can someone explain pseudocode further?(2 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));

}

}

}(7 votes)

- How can no words or no letters be a palindrome?(3 votes)
- An empty string reads the same forwards and backwards.(5 votes)

- Can you please tell me in which language the challenge is written?(1 vote)
- its java script.(1 vote)

- I'm feeling lost on Step 1 of the challenge. Can someone help me on base case 1?

// base case #1

if (0 <= 1){ return true;}(2 votes)- You need to check the length of the string. How would you find the length of a string ?(1 vote)

- // 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?(1 vote)- The instructions say base case 2 is:

"If the first and last characters of the string are**different**"(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(2 votes)

- i'm facing problem in recursive case.Can anyone tell me , after striking off the first and the last character by calling the middleCharacters function, how should i proceed with the resulting string. Means, how should i proceed with "oto"...(0 votes)
- You handle the smaller strings, the same way that you handled the bigger strings (this is why it is a recursive solution), until you finally hit the base case of 0 or 1 characters.(4 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);(1 vote)- seriously, how did you get it??(2 votes)

- how can this be used in maths, (palindromic numbers) and how can they be used in our daily lives(1 vote)