Ferozeh dot Com
Expert advice on tech interviews !
about ferozeh

Ferozeh

Similar Questions


permutations of a string


delete a word in a string


reverse a string


convert integer to string

Question

Difficulty Level: 1

  • Write code to detect a palindrome?

Solution

Explanation Quality:

Explanation Quality:5

Another simple question which is almost similar to the question of reversing a string which is discussed here.

Say we have the following palindrome. A palindrome is a string of words which when reversed forms the same word. Note entire sentence can be palindromes too but we only solve the case of detecting word palindromes.

We declare two pointers, each pointing to the start and the end of the string. Next we check if the characters pointed to by the two pointer are the same or not. If they aren't then it's definitely not a palindrome but if they are then it's a chance that the given string might be a palindrome and we must continue sacanning the string to make sure. Here's the code:

int i = 0;

int j = length_of_string - 1; //array index starts from 0

while( i < j){

 if(string[i] != string[j]){
  cout<<"NOT A PALINDROME"<<endl;
  exit(0);
 }

 i++;
 j--;

}

cout<<"YES A PALINDROME"<<endl;

Note the condition for the while loop. If the palindrom consists of even number of characters then the loop runs on every character. However if the palindrome consists of an odd number of characters then the loop exists without checking the middle element which is ok since the middle element appears at the same position when reversed and doesn't matter.

 




Previous Next