Facebook Interview Question for Software Engineers


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
3
of 3 vote

public static void main(String[] args) {
System.out.println(isPalindrome("A man, a plan, a canal, Panama! "));
// abbacabba
System.out.println(isPalindrome("#!@$% Ab !@%!@ B  !%@!%!@% a  1%!@% C  !@%!@% a  1%!@% B 1%!@% b @!#)(*) A "));

System.out.println(isPalindrome("TEST"));
}

public static boolean isPalindrome(String s) {
char a, b;
int valA = 0, valB = 0;
int i = 0, j = s.length() - 1;		
while(i < j) {
	a = Character.toLowerCase(s.charAt(i));
	b = Character.toLowerCase(s.charAt(j));
	valA = a - 'a';
	valB = b - 'a';
	
	if(valA < 0 || valA >= 26) {
		i++;
	}
	if(valB < 0 || valB >= 26) {
		j--;
	}			
				
	if((valA >= 0 && valA < 26) && (valB >= 0 && valB < 26) && a != b) {
		return false;
	} else if((valA >= 0 && valA < 26) && (valB >= 0 && valB < 26) && a == b) {
		i++;
		j--;
	}
}
return true;
}

// output:
true
true
false

- guilhebl May 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
3
of 3 votes

Good answer. Just one point. You should compare a and b with equals not "==" since a and b are Character pointers not char variables. or you could just use valA and valB also since you are comparing in the begining you could simplify the if statment by use chain if else-if statements like below:

if(valA < 0 || valA >= 26) {
		i++;
	}else if(valB < 0 || valB >= 26) {
		j--;
	}else	if( valA != valB) {
		return false;
	} else{
		i++;
		j--;
	}

- amirtar May 05, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@amirtar in java char is a primitive type, making comparison with "==" completely safe.

- Anonymous May 06, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The above solution is not working for "1212"...
Try this.....

public class Test{
public static void main(String [] args)
{
if (isPalindrome("1221"))
System.out.println("true");
else
System.out.println("false");
}

public static boolean isPalindrome(String str){
int stringLength=str.length();

if (stringLength==1)
return true;

int i=0;
int j=stringLength-1;

while (i<j){
while (!((Character.toLowerCase(str.charAt(i))>=97 && Character.toLowerCase(str.charAt(i))<=122) || (Character.toLowerCase(str.charAt(i))>=48 &&Character.toLowerCase(str.charAt(i))<=57)))
i++;
while (!((Character.toLowerCase(str.charAt(j))>=97 && Character.toLowerCase(str.charAt(j))<=122) || (Character.toLowerCase(str.charAt(j))>=48 &&Character.toLowerCase(str.charAt(j))<=57)))
j--;
if(Character.toLowerCase(str.charAt(i))!=Character.toLowerCase(str.charAt(j)))
return false;
i++;
j--;
}
return true;
}
}

- piy October 28, 2015 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

Here is C++ version:

bool IsAlphabet(char c)
{
	return ((c >='a' && c<='z')||(c>='A' &&c<='Z'));
}

bool IsSame(char s , char d)
{	
	int lowbase_a = s-'a';
	int upperbase_a = s-'A';
	int lowbase_d = d-'a';
	int upperbase_d = d - 'A';
	return ((lowbase_a == lowbase_d) ||(upperbase_a == upperbase_d) || (lowbase_a == upperbase_d) || (upperbase_a) == (lowbase_d));
}
bool IsPanlindrome(const char * str, int length)
{
	int s = 0;
	int  e = length;
	while (s < e)
	{
		if (!IsAlphabet(str[s]))
		{
			s++;
			continue;
		}
		if (!IsAlphabet(str[e]))
		{
			e--;
			continue;
		}

		if (IsSame(str[s], str[e]))
		{
			s++;
			e--;
		} else
			return false;
	}
	return true;
}

- hankm2004 June 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

public static void main(String[] args) {
		System.out.println(isPal("A man, a plan, a canal, Panama!"));
		System.out.println(isPal("Madam I'm Adam"));
		
	}
	
	public static boolean isPal(String rest) {
	    if (rest.trim().length() < 2) return true;
	    char first = getCharOrSkip(rest, 0, 1);
	    char last = getCharOrSkip(rest, rest.length()-1, -1);
	    int firstPos = rest.indexOf(first);
	    int lastPost = rest.lastIndexOf(String.valueOf(last));
	    return firstPos == lastPost || (toLower(first) == toLower(last) && isPal(rest.substring(firstPos+1, lastPost)));
	}
	
	public static char getCharOrSkip(String str, int pos, int direction) {
		char c = str.charAt(pos);
		return ((c >= 'A' && c<= 'Z') || (c >= 'a' && c <= 'z')) ? c : getCharOrSkip(str, pos + direction, direction);
	}
	
	public static char toLower(char c) {
		return (c >= 'a') ? (char) (c - 32) : c;
	}

- Thiago Locatelli May 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

In C#

static void Main(string[] args)
        {
            PalindromeCheck("A man, a plan, a canal, Panama!");
            Console.ReadLine();
        }
        static void PalindromeCheck(String palindrom)
        { 
            int j=palindrom.Length-1;
            int i=0;
            bool isPalindrom = true;
            do
            {
                char c1 = Char.ToLower(palindrom[i]);
                char c2 = Char.ToLower(palindrom[j]);
                while (!Char.IsLetter(c1) && !Char.IsNumber(c1))
                {
                    i++;
                    c1 = Char.ToLower(palindrom[i]);                 
                }

                while (!Char.IsLetter(c2) && !Char.IsNumber(c2))
                {
                    j--;
                    c2 = Char.ToLower(palindrom[j]);
                }
                i++;
                j--;
                if (c1 != c2) { isPalindrom = false; }
            } while (i<j && isPalindrom==true);

            Console.WriteLine("Is Palindrom?: " + isPalindrom);
        }
    }

- aldojm April 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// Ignores everything except alpha characters
bool isPalindromeAlpha(char* inputString, char* startPos, char* endPos)
{
	bool isPalindrome = true;

	char charToCompare1 = '\0';
	char charToCompare2 = '\0';
	while (startPos < endPos)
	{
		// Skip over characters that are not letters
		while ( ((*startPos < 'a' || *startPos > 'z') && (*startPos < 'A' || *startPos > 'Z')) && startPos < endPos)
		{
			startPos++;
		}

		while (((*endPos < 'a' || *endPos > 'z') && (*endPos < 'A' || *endPos > 'Z')) && endPos > startPos)
		{
			endPos--;
		}

		// Make all letters lowercase
		charToCompare1 = *startPos;
		if (charToCompare1 >= 'A' && charToCompare1 <= 'Z')
		{
			charToCompare1 = 'a' + (charToCompare1 % 'A');
		}

		charToCompare2 = *endPos;
		if (charToCompare2 >= 'A' && charToCompare2 <= 'Z')
		{
			charToCompare2 = 'a' + (charToCompare2 % 'A');
		}

		if (charToCompare1 != charToCompare2)
		{
			isPalindrome = false;
			break;
		}
		else
		{
			startPos++;
			endPos--;
		}
	}

	return isPalindrome;
}

int _tmain(int argc, _TCHAR* argv[])
{
	char inputString[] = "A man, a plan, a canal, Panama!";
	//char inputString[] = "#!@$% Ab !@%!@ B  !%@!%!@% a  1 % !@% C  !@%!@% a  1 % !@% B 1 % !@% b @!#)(*) A ";
	cout << inputString << (isPalindromeAlpha(inputString, inputString, inputString + strlen(inputString) - 1) ? " is " : " is not ") << "a palindrome";
	
	return 0;
}

- CareerCupDom May 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is my two cents:

public static void main(String[] args) {
		System.out.println(isPal("A man, a plan, a canal, Panama!"));
		System.out.println(isPal("Madam I'm Adam"));
		System.out.println(isPal("aba"));
		System.out.println(isPal("#!@$% Ab !@%!@ B  !%@!%!@% a  1%!@% C  !@%!@% a  1%!@% B 1%!@% b @!#)(*) A"));
		System.out.println(isPal("TEST"));	
	}
	
	public static boolean isPal(String rest) {
	    if (rest.trim().length() < 2) return true;
	    char first = getCharOrSkip(rest, 0, 1);
	    char last = getCharOrSkip(rest, rest.length()-1, -1);
	    int firstPos = rest.indexOf(first);
	    int lastPost = rest.lastIndexOf(String.valueOf(last));
	    return firstPos == lastPost || (toLower(first) == toLower(last) && isPal(rest.substring(firstPos+1, lastPost)));
	}
	
	public static char getCharOrSkip(String str, int pos, int direction) {
		char c = str.charAt(pos);
		return ((c >= 'A' && c<= 'Z') || (c >= 'a' && c <= 'z')) ? c : getCharOrSkip(str, pos + direction, direction);
	}
	
	public static char toLower(char c) {
		return (c >= 'a') ? (char) (c - 32) : c;
	}

- Thiago Locatelli May 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def checkPalindrome(string):
    startindex = 0
    endindex = len(string) - 1
    
    isPalindrome = True
    
    while True:
        if endindex <= startindex:
            break 
        startchar = string[startindex]
        endchar = string[endindex]
        if not startchar.isalpha():
            startindex += 1
            continue
        if not endchar.isalpha():
            endindex -= 1
            continue
        if startchar.lower() != endchar.lower():
            isPalindrome = False
            break
        else:
            startindex += 1
            endindex -= 1
          
    return isPalindrome
print checkPalindrome('A man, a plan, a canal, Panama!')

- mukund1776 May 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isPalindromeDev(String input) {
int i = 0, j = input.length()-1;
char[] chars = input.toLowerCase().toCharArray();
while( i < j ) {
while((chars[i] - 'a') < 0 || (chars[i] - 'a') > 25)
i++;
while((chars[j] - 'a') < 0 || (chars[j] - 'a') > 25)
j--;
if(chars[i] != chars[j]) {

return false;
}
i++;
j--;
}
return true;
}

- hamidreza.maghbooli May 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hamidreza, in code eshkal dare. You should not make a copy of input. You made a copy of input here:

char[] chars = input.toLowerCase().toCharArray();

- amirtar May 05, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isPalindrome(String str){
return removeSpecialChars(str).toString().equalsIgnoreCase(removeSpecialChars(str).reverse().toString());
}

public static StringBuilder removeSpecialChars(String str){
StringBuilder sb = new StringBuilder();

char[] chars = str.toCharArray();

for (int i = 0; i < chars.length; i++) {
if(((chars[i] >= 'A' && chars[i]<= 'Z') || (chars[i] >= 'a' && chars[i] <= 'z')) ){
sb.append(chars[i]);
}
}
return sb;
}

- Jim T. May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isPalindrome(String str){
		  return removeSpecialChars(str).toString().equalsIgnoreCase(removeSpecialChars(str).reverse().toString());
	}
	
	public static StringBuilder removeSpecialChars(String str){
		StringBuilder sb = new StringBuilder();
		 
		char[] chars = str.toCharArray();
		
		for (int i = 0; i < chars.length; i++) {
			if(((chars[i] >= 'A' && chars[i]<= 'Z') || (chars[i] >= 'a' && chars[i] <= 'z')) ){
				sb.append(chars[i]);
			}
		}
		return sb;
	}

- Jim T. May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}

var endPointer = source.Length-1;
var startPointer = 0;

while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}

- .netCoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
        {
            if (string.IsNullOrEmpty(source))
            {
                return false;
            }

            var endPointer = source.Length-1;
            var startPointer = 0;

            while (startPointer < endPointer)
            {
                //get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets 
                //ignore case of course.
                var valA = Char.ToLower(source[startPointer]) - 'a';
                var valB = Char.ToLower(source[endPointer]) - 'a';
                if (valA < 0 || valA > 26)
                {
                    startPointer++;
                }
                else if (valB < 0 || valB > 26)
                {
                    endPointer--;
                }
                else if (valA != valB)
                {
                    return false;
                }
                else {
                    startPointer++;
                    endPointer--;
                }
            }
            return true;
        }

- .netCoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
        {
            if (string.IsNullOrEmpty(source))
            {
                return false;
            }

            var endPointer = source.Length-1;
            var startPointer = 0;

            while (startPointer < endPointer)
            {
                //get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets 
                //ignore case of course.
                var valA = Char.ToLower(source[startPointer]) - 'a';
                var valB = Char.ToLower(source[endPointer]) - 'a';
                if (valA < 0 || valA > 26)
                {
                    startPointer++;
                }
                else if (valB < 0 || valB > 26)
                {
                    endPointer--;
                }
                else if (valA != valB)
                {
                    return false;
                }
                else {
                    startPointer++;
                    endPointer--;
                }
            }
            return true;

- .netCoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}

var endPointer = source.Length-1;
var startPointer = 0;

while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}

- .netCoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
        {
            if (string.IsNullOrEmpty(source))
            {
                return false;
            }

            var endPointer = source.Length-1;
            var startPointer = 0;

            while (startPointer < endPointer)
            {
                //get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets 
                //ignore case of course.
                var valA = Char.ToLower(source[startPointer]) - 'a';
                var valB = Char.ToLower(source[endPointer]) - 'a';
                if (valA < 0 || valA > 26)
                {
                    startPointer++;
                }
                else if (valB < 0 || valB > 26)
                {
                    endPointer--;
                }
                else if (valA != valB)
                {
                    return false;
                }
                else {
                    startPointer++;
                    endPointer--;
                }
            }
            return true;

}

- .netCoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
        {
            if (string.IsNullOrEmpty(source))
            {
                return false;
            }

            var endPointer = source.Length-1;
            var startPointer = 0;

            while (startPointer < endPointer)
            {
                //get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets 
                //ignore case of course.
                var valA = Char.ToLower(source[startPointer]) - 'a';
                var valB = Char.ToLower(source[endPointer]) - 'a';
                if (valA < 0 || valA > 26)
                {
                    startPointer++;
                }
                else if (valB < 0 || valB > 26)
                {
                    endPointer--;
                }
                else if (valA != valB)
                {
                    return false;
                }
                else {
                    startPointer++;
                    endPointer--;
                }
            }
            return true;
        }

- netCoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}

var endPointer = source.Length-1;
var startPointer = 0;

while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
}

- .netcoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
        {
            if (string.IsNullOrEmpty(source))
            {
                return false;
            }

            var endPointer = source.Length-1;
            var startPointer = 0;

            while (startPointer < endPointer)
            {
                //get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets 
                //ignore case of course.
                var valA = Char.ToLower(source[startPointer]) - 'a';
                var valB = Char.ToLower(source[endPointer]) - 'a';
                if (valA < 0 || valA > 26)
                {
                    startPointer++;
                }
                else if (valB < 0 || valB > 26)
                {
                    endPointer--;
                }
                else if (valA != valB)
                {
                    return false;
                }
                else {
                    startPointer++;
                    endPointer--;
                }
            }
            return true;
        }

- .netcoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
        {
            if (string.IsNullOrEmpty(source))
            {
                return false;
            }

            var endPointer = source.Length-1;
            var startPointer = 0;

            while (startPointer < endPointer)
            {
                //get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets 
                //ignore case of course.
                var valA = Char.ToLower(source[startPointer]) - 'a';
                var valB = Char.ToLower(source[endPointer]) - 'a';
                if (valA < 0 || valA > 26)
                {
                    startPointer++;
                }
                else if (valB < 0 || valB > 26)
                {
                    endPointer--;
                }
                else if (valA != valB)
                {
                    return false;
                }
                else {
                    startPointer++;
                    endPointer--;
                }
            }
            return true;
        }

- .netDecoder May 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This would work in C#

public static bool chackIfPalindrom(string s)
        {
            if (string.IsNullOrEmpty(s) || s.Length < 2)
            {
                return false;
            }
            else
            {
                int startIdex = 0;
                int endIndex = s.Length-1;
                while (startIdex <= endIndex)
                {
                    while (isSpecialChar(s[startIdex]))
                    {
                        startIdex++;
                    }
                    while (isSpecialChar(s[endIndex]))
                    {
                        endIndex--;
                    }
                    if (s[startIdex].ToString().ToLower() != s[endIndex].ToString().ToLower())
                    {

                        return false;
                    }
                    else
                    {
                        startIdex++;

                        endIndex--;
                    }
                    
                }
                return true;
               

            }
        }
        public static bool isSpecialChar(char s)
        {
            int val =(int)s;
            if (val >= 20 && val <= 47)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

- Raj May 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isPaldrome(String str) {

		if (str == null || str.length() == 0)
			return false;

		int i = 0;
		int j = str.length() - 1;

		while (i < j) {
			char left = str.charAt(i);
			char right = str.charAt(j);
			while (!Character.isAlphabetic(left) && i < str.length()) {
				left = str.charAt(++i);
			}
			while (!Character.isAlphabetic(right) && j >= 0) {
				right = str.charAt(--j);
			}

			if (Character.toLowerCase(right) != Character.toLowerCase(left))
				return false;

			i++;
			j--;
		}
		return true;
	}

- romina May 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
  char* str;
  char l;
  char r;
  int len;
  int i;
  int j;
  int b;
  
  if ( argc != 2 ) {
    printf("num args is %d\n", argc);
    return 1;
  }
  
  str = argv[1];
  len = strlen(str);
  
   printf("Str read is %s\n", str);
  
  for (i = 0, j = len, b = 1; b && i < j ; ) {
    if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
      if ((str[j] >= '0' && str[j] <= '9') || (str[j] >= 'a' && str[j] <= 'z') || (str[j] >= 'A' && str[j] <= 'Z')) {
        if (str[i] >= 0x41 && str[i] <= 0x5A) {
          l = 0x20;
        } else {
          l = 0x00;
        }
        if (str[j] >= 0x41 && str[j] <= 0x5A) {
          r = 0x20;
        } else {
          r = 0x00;
        }
        if ( str[i] + l != str[j] + r) {
          printf("breaking here because %c at %d != %c at %d", str[i], i, str[j], j );
          b = 0;
        }
        i ++;
        j --;
      } else {
        j --;
      }
    } else {
      i ++;
    }
  }
  
  if (b) {
    printf("Str %s is a Palindrome\n", str);
  }
}

- Shoaib June 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In C, be careful if you use ! on bash, quote your string with single quotes

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
  char* str;
  char l;
  char r;
  int len;
  int i;
  int j;
  int b;
  
  if ( argc != 2 ) {
    printf("num args is %d\n", argc);
    return 1;
  }
  
  str = argv[1];
  len = strlen(str);
  
   printf("Str read is %s\n", str);
  
  for (i = 0, j = len, b = 1; b && i < j ; ) {
    if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
      if ((str[j] >= '0' && str[j] <= '9') || (str[j] >= 'a' && str[j] <= 'z') || (str[j] >= 'A' && str[j] <= 'Z')) {
        if (str[i] >= 0x41 && str[i] <= 0x5A) {
          l = 0x20;
        } else {
          l = 0x00;
        }
        if (str[j] >= 0x41 && str[j] <= 0x5A) {
          r = 0x20;
        } else {
          r = 0x00;
        }
        if ( str[i] + l != str[j] + r) {
          printf("breaking here because %c at %d != %c at %d", str[i], i, str[j], j );
          b = 0;
        }
        i ++;
        j --;
      } else {
        j --;
      }
    } else {
      i ++;
    }
  }
  
  if (b) {
    printf("Str %s is a Palindrome\n", str);
  }

}

- Shoaib June 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public boolean isPalindrome(String strr){
		if( strr == null || strr.length() <= 0){
			return true;
		}
		
		char[] arr = strr.toCharArray();
		int i = 0, j = arr.length -1;
		while(i < j){
			//check for lowercase, uppercase
			//check for unwanted characters..
			char cI = arr[i];
			
			//alpha numeric characters..
			if(!isalphanumericCharacter(cI)){
				i++;
				continue;
			}
			
			char cJ = arr[j];
			//alpha numeric characters..
			if(!isalphanumericCharacter(cJ)){
				j--;
				continue;
			}
			
			if((cJ == cI) || Math.abs(cI-cJ) == 32){
				j--;
				i++;
			}else{
				return false;
			}
			
		}
		
		return true;
		
	}
	
	public boolean isalphanumericCharacter(char c){
		int value = (int) c;
		if((value >= 48 && value <= 57)
			|| (value >= 65 && value <= 90)
			|| (value >= 97 && value <= 122)
				){
			return true;
		}
		return false;
	}

- Amandeep Dhanjal June 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>

bool palindrome(const std::string &string) {
  int a = -1;
  
  int b = (int)string.size();
  
  while (true) {
    do {
      ++a;
    } while(a < b && !isalpha(string[a]));
    
    do {
      --b;
    } while (a < b && !isalpha(string[b]));
    
    if (a >= b) {
      return true;
    }
    
    if (toupper(string[a]) != toupper(string[b])) {
      return false;
    }
  }
}

int main(int argc, const char * argv[]) {
  std::cout << palindrome("A man, a plan, a canal, Panama!") << std::endl;

}

- Allen June 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I used Swift to answer this. I separated the solution into two methods.
1. Sanitise the string.
2. to find out if said string is a palindrome using recursion.

PS:
• We only need to sanitise the string once.
• Using NSString substringWithRange is much easier/cleaner solution

func sanitization(str: String) ->String {
    
    let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet
    var strippedString = str.componentsSeparatedByCharactersInSet(charactersToRemove)
    var cleanString = "".join(strippedString)
    return cleanString.lowercaseString
}

func palindrome(str: String) -> Bool {
    
    if (count(str) <= 1) {
        return true
    }
        for aChar in str {
            
            let results = palindrome(str.substringWithRange( Range<String.Index>(start: advance(str.startIndex, 1), end: advance(str.startIndex, count(str) - 1))))
            let boundryWords = str[str.startIndex] ==  str[advance(str.startIndex, count(str) - 1)]
            return ( boundryWords && results)
        }
    return false
}

let test = ""
let test1 = "A car, a man, a maraca."
let test2 = "Are we not drawn onward to new era?"
let test3 = "Not a palindrome, no chance"
let test4 = "A"
let test5 = "Naughty dog"

palindrome(sanitization(test1))
palindrome(sanitization(test2))
palindrome(sanitization(test3))
palindrome(sanitization(test4))
palindrome(sanitization(test5))

Output:

true
true
false
true
false

- Edwin June 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Objective-C Solution:

- (BOOL)validatePalindrome:(NSString *)stringToEval
{
  stringToEval = [self cleanString:stringToEval];
  NSUInteger startIndex = 0;
  NSUInteger endIndex = stringToEval.length-1;
  
  while (startIndex < endIndex) {
    if (![[stringToEval substringWithRange:NSMakeRange(startIndex, 1)] isEqualToString:[stringToEval substringWithRange:NSMakeRange(endIndex, 1)]]) {
      return NO;
    }
    startIndex++;
    endIndex--;
  }
  return YES;
}

- (NSString *)cleanString:(NSString *)stringToClean
{
  NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
  NSString *newString = [[stringToClean componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];
  return newString;
}

- JH June 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

javascript version

var sample = "A man, a plan, a canal, Panama!"

console.log(isPal(sample));

function isPal (str){
  var i = 0, j = str.length-1;
  
  while(i < j){
    if ( isLetter(str[i]) && isLetter(str[j]) && str[i].toLowerCase() != str[j].toLowerCase()){
      return false;
    }
    if ( isLetter(str[i]) && isLetter(str[j]) ) {
      i++;
      j--;
    }
    else{
      if (!isLetter(str[i])) i++;
      if (!isLetter(str[j])) j--
    }
    console.log(str[i], str[j], i, j);
  }
  return true;
}

function isLetter (c){
  return (c <= 'Z' && c >= 'A') || (c <= 'z' && c >= 'a');
}

- Anonymous August 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C++ version

#include <iostream>
#include <string>
using namespace std;

inline bool IsValid(char c)
{
  return (c >= 'a' && c <= 'z') //lowercase alpha
         || (c >= 'A' && c <= 'Z') //Uppercase alpha
         || (c >= '0' && c <= '9'); //Numerics
}

inline char ToLower(char c)
{
    if ( c >= 'A' && c <= 'Z')
      return c - 'A' + 'a';
    return c;
}

bool IsPalindrome( string str)
{
  string::iterator i = str.begin();
  string::iterator j = str.end() - 1;
  string::iterator beg = str.begin();
  string::iterator end = str.end();
  do {
     while( i != end && !IsValid(*i) ) ++i; // get valid char from current i position
     while( !IsValid(*j) ) { --j; if (j == beg) break; } // get valid char from current j position
     
     if ( i > j)
       break;
     if ( ToLower( *i) != ToLower( *j))
       return false;
     ++i; --j;
  } while(1);
  return true;
}

- borisshr August 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

One more

#include <iostream>
#include <string>
using namespace std;

inline bool IsValid(char c)
{
  return (c >= 'a' && c <= 'z') //lowercase alpha
         || (c >= 'A' && c <= 'Z') //Uppercase alpha
         || (c >= '0' && c <= '9'); //Numerics
}

inline char ToLower(char c)
{
    if ( c >= 'A' && c <= 'Z')
      return c - 'A' + 'a';
    return c;
}

bool IsPalindrome( string str)
{
  string::iterator i = str.begin();
  string::iterator j = str.end() - 1;
  while ( i < j ) {
     if ( !IsValid(*i) ) { ++i; continue; }
     if ( !IsValid(*j) ) { --j; continue; }
     
     if ( ToLower( *i) != ToLower( *j))
       return false;
     ++i;--j;
  }
  return true;
}

- borisshr August 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public boolean checkPalindrome(char[] letters,int length)
	{
		
		int i=0;
		int j=length-1;
		
		
		boolean flag=true;
		boolean flag2=false;
		
		
		
		while( i < j && flag == true )
		{
			while(!Character.isLetter(letters[i]) && i<length)
				i++;
			
			while(!Character.isLetter(letters[j]) && i<length && i < j)
				j--;
			
			if(i < j)
			{
			
				if(letters[i]==letters[j])
				{
					i++;
					j--;
					flag2=true;
			  
				}
				else
				{
				   flag =false;	
				}
				
			
			}
			
		   
		}

	
	    return flag&&flag2;
	}

- lb August 14, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Another javascript version:

function isPalindrome(str){
        var length = str.length,
            left = 0,
            right = length - 1,
            a = null,
            b = null,
            aIsLetter = false,
            bIsLetter = false,
            itReallyIs = true
            ;

        function isLetter(str) {
            return /^[a-z0-9]+$/i.test(str);
        }

        while(left < length && right >= 0){
            a = str[left].toLowerCase();
            b = str[right].toLowerCase();

            aIsLetter = isLetter(a);
            bIsLetter = isLetter(b);

            if(aIsLetter && bIsLetter){ // both are letters, just compare
                if(a !== b){
                    itReallyIs = false;
                    break;
                }
                else{
                    ++left;
                    --right;
                }
            }
            else{ // only shift if non-alphanumeric
                if(!aIsLetter){
                    ++left;
                }
                if(!bIsLetter){
                    --right;
                }
            }
        }
        return itReallyIs;
    }

- Alex August 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Another javascript version:

function isPalindrome(str){
        var length = str.length,
            left = 0,
            right = length - 1,
            a = null,
            b = null,
            aIsLetter = false,
            bIsLetter = false,
            itReallyIs = true
            ;

        function isLetter(str) {
            return /^[a-z0-9]+$/i.test(str);
        }

        while(left < length && right >= 0){
            a = str[left].toLowerCase();
            b = str[right].toLowerCase();

            aIsLetter = isLetter(a);
            bIsLetter = isLetter(b);

            if(aIsLetter && bIsLetter){ // both are letters, just compare
                if(a !== b){
                    itReallyIs = false;
                    break;
                }
                else{
                    ++left;
                    --right;
                }
            }
            else{ // only shift if non-alphanumeric
                if(!aIsLetter){
                    ++left;
                }
                if(!bIsLetter){
                    --right;
                }
            }
        }
        return itReallyIs;
    }

- jSancho August 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

val p = "A man, a plan, a canal, Panama!"
  
  println(isP(p))
  
  def isP(s: String): Boolean = {
    var start: Int = 0
    var end: Int = s.size - 1
    
    while (start <= end) {
      while (s(start).toString matches "[^a-zA-Z0-9]{1}") {
        start = start + 1
      }
      
      while (s(end).toString matches "[^a-zA-Z0-9]{1}") {
        end = end - 1
      }
      
      if (s(start).toLower != s(end).toLower) {
        return false
      }
      
      start = start + 1
      end = end - 1
    }
    
    true
  }

- scala September 15, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static bool IsPalindromeOnlyChars(string input)
    {
        int i = 0, j = input.Length - 1;
        input = input.ToLower();

        while (i < j)
        {
            while (!(('a' <= input[i] && input[i] <= 'z')))
                i++;
            while (!(('a' <= input[j] && input[j] <= 'z')))
                j--;

            if (input[i] != input[j])
                return false;

            i++;
            j--;
        }
        return true;
    }

- codealtecdown September 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

bool IsChar(char input){

	if (input >= ‘a’ && input <= ‘z’)
		return true;
	else if (input >= ‘A’ && input <= ‘Z’)
		return true;
	else
		return false;
}

bool Palindrome(char * input){
	int size = 0;
	char *tmp = input;

	while(*tmp != ‘\0’){
		size++;
		tmp++;
	}
	

	int front = 0;
	int back = size - 1;


	while (front < back){
		while( !IsChar(input[front])){
			front ++;
		}

		while( !IsChar(input[back])){
			back —;
		}
	
		if (tolower(input[front]) == tolower( input[back]) ){
			front ++;
			back —;
		}
		else
			return false;

	}	

	return true;
}

- hiuhchan September 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Not storing a copy of the string processed:

def isPalindrome1(sentence):
	
	if ''.join([i for i in sentence.lower() if i.isalpha() ])==''.join([i for i in sentence.lower() if i.isalpha() ])[::-1]: return True
	return False

- murali October 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In php

<?php
$w = 'A man, a plan, a canal, Panama!';

$w = preg_replace("/[^A-Za-z0-9]/", '', strtolower($w));
$c = strlen($w);

for ($x=0,$y=$c-1;$x<floor($c / 2);$x++,$y--,($w[$x]!=$w[$y]) ? die('false') : true);

die('true');
?>

- mboi.coy April 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In php:

<?php
$w = 'A man, a plan, a canal, Panama!';

$w = preg_replace("/[^A-Za-z0-9]/", '', strtolower($w));
$c = strlen($w);

for ($x=0,$y=$c-1;$x<floor($c / 2);$x++,$y--,($w[$x]!=$w[$y]) ? die('false') : true);

die('true');
?>

- portege April 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Move two counter from start and end of the string, skip the non chracters.

private static boolean isPalindrom(final String str) {
	        if (str == null || str.isEmpty())
	            return false;
	        String testStr = str.toLowerCase();
	        int i = 0;
	        int j = testStr.length() - 1;
	        // start two counters from start and end moving towards each other
	        while (i != j) {
	        	// if not valid char, skip
	        	if(!Character.isLetterOrDigit(testStr.charAt(i))) {
	        		i++;
	        		continue;
	        	}
	        	if(!Character.isLetterOrDigit(testStr.charAt(j))) {
	        		j--;
	        		continue;
	        	}
	            if (testStr.charAt(i) != testStr.charAt(j))
	                return false;
	            i++;
	            j--;
	        }
	        return true;
	    }

- Anonymous August 23, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More