Skip to content

Palindromes

Determining Palindromes in C#

A palindrome is a sequence that reads the same backward as forward. You can use method overloading to create two IsPalindrome methods: one for strings and one for integers.

public static bool IsPalindrome(string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    str = str.ToLower().Replace(" ", "");
    return str.SequenceEqual(str.Reverse());
}

Integer Palindrome Method

public static bool IsPalindrome(int number)
{
    string numStr = number.ToString();
    return numStr.SequenceEqual(numStr.Reverse());
}

Examples

Console.WriteLine(IsPalindrome("A man a plan a canal Panama")); // True
Console.WriteLine(IsPalindrome("hello")); // False
Console.WriteLine(IsPalindrome(12321)); // True
Console.WriteLine(IsPalindrome(12345)); // False

These methods use LINQ’s SequenceEqual and Reverse for efficient comparison. The string method converts to lowercase and removes spaces to handle phrase palindromes.

By using method overloading, you can call IsPalindrome with either a string or an integer, and C# will automatically choose the appropriate method based on the argument type.

Remember, for very large numbers or strings, you might need to implement a more memory-efficient algorithm.

Large Input

For very large numbers or strings, you can implement a more memory-efficient algorithm using a two-pointer approach. This method avoids creating new strings or reversing the entire input, which can be memory-intensive for large inputs. Here’s how you can modify IsPalindrome methods to be more efficient:

public static bool IsPalindrome(string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    int left = 0;
    int right = str.Length - 1;

    while (left < right)
    {
        while (left < right && !char.IsLetterOrDigit(str[left]))
            left++;
        while (left < right && !char.IsLetterOrDigit(str[right]))
            right--;

        if (char.ToLower(str[left]) != char.ToLower(str[right]))
            return false;

        left++;
        right--;
    }

    return true;
}```

```csharp
public static bool IsPalindrome(int number)
{
    if (number < 0)
        return false;

    int original = number;
    int reversed = 0;

    while (number > 0)
    {
        int digit = number % 10;
        reversed = reversed * 10 + digit;
        number /= 10;
    }

    return original == reversed;
}

These implementations are more memory-efficient because:

For strings:

For integers:

These methods have a time complexity of O(n) where n is the length of the string or the number of digits in the integer, but they use O(1) space complexity, making them more efficient for very large inputs.