Another common interview question is to write a function to detect if a string is a palindrome. For those who may not be aware a palindrome is the same word spelt backwards as forwards eg "RACECAR".

Places tend to ask this because it can be solved in multiple ways. The two mainmethods are either using a for loop or using recursion. I don't think the recusion method is an advantage in c# because of the lack of pointers. So that method is going to be skipped here. The reason why they ask this is because it has a nice catch on how the issue of how to deal with an odd number of letters. This is actually very simple since the odd letter is in the middle it will be compared to its self. So there is never any need to compare the middle letter. An example is "RAC" "E" "CAR".

Here is a solution that will work for both even and odd cases ..

public static bool IsPalindrome(string str)
{
    for (int i = 0; i < str.Length / 2; i++)
        if (str[i] != str[str.Length - (i + 1)])
            return false;
    return true;
}

Something that is interesting is that as well as a simple technical test the interviewer can challenge on the functionality of the operation of the odd case. Sometimes they do this to see if the person is going to defend them self or just role over and show a lack of confidence in their solution.



Did You find this page useful?

Yes No



Last Modified: 23 February 2017

Releated Posts


2012-01-30 - C - The string reverse
2012-01-27 - C - Palindrome
2011-10-27 - CSharp - Number Of Cores and Processors
2011-10-04 - CSharp - Thread Queue Example
2011-09-29 - CSharp - Background Thread / Task
2011-09-17 - CSharp - Lookup Hostname
2011-08-29 - C Sharp - StopWatch, The high resolution timer
2011-08-29 - CSharp - IsGuid
2011-08-26 - CSharp - Convert Between Meters and Feet
2011-08-23 - CSharp - ThreadPool and Windows Forms
2011-08-10 - C Sharp - MD5Sum / SHASum
2011-07-22 - CSharp - Fibonacci sum
2011-07-13 - CSharp - Palindrome
2011-07-11 - CSharp - The string Reverse
2011-07-10 - CSharp - Interviews FizzBuzz
2011-06-27 - CSharp - HowTo Parse a URL
2011-06-22 - CSharp - Extending any class
2011-06-13 - ASPNET - Login by username or email
2011-05-12 - CSharp - ASPNET Logoff
2011-03-07 - C Sharp - Windows Logoff
2011-03-02 - ASPNET - Dynamic Controls
2011-03-01 - C Sharp - Resize an image by size of height
2011-02-23 - C Sharp / MSSQL Get inserted value of NEWSEQUENTIALID()
2011-02-10 - CSharp - Wake on Lan (WOL) Packet
2011-02-10 - CSharp - Shutdown or reboot windows
2011-02-06 - C Sharp - Gridview Bound Yes No
2011-02-05 - MSSQL - Levenshtein
2011-01-30 - MSSQL - Enabling CLR Functions
2011-01-30 - MSSQL - Adding MD5 checksum support
2011-01-30 - MSSQL - RegEx Support
2011-01-30 - MSSQL - Adding SHASum support