C# Program to Check Palindrome String
string reversed = new string(input.Reverse().ToArray()); and then checking input == reversed.Examples
How to Think About It
Algorithm
Code
using System; using System.Linq; class Program { static void Main() { Console.Write("Enter a string: "); string input = Console.ReadLine(); string reversed = new string(input.Reverse().ToArray()); if (input == reversed) { Console.WriteLine($"{input} is a palindrome."); } else { Console.WriteLine($"{input} is not a palindrome."); } } }
Dry Run
Let's trace the input 'madam' through the code.
Input string
input = 'madam'
Reverse string
reversed = 'madam'
Compare strings
input == reversed -> 'madam' == 'madam' is true
Output result
Print 'madam is a palindrome.'
| Step | input | reversed | Comparison Result |
|---|---|---|---|
| 1 | madam | ||
| 2 | madam | madam | |
| 3 | madam | madam | true |
Why This Works
Step 1: Reverse the string
We use input.Reverse() to get characters in reverse order and create a new string from them.
Step 2: Compare original and reversed
If the original string and reversed string are exactly the same, it means the string reads the same forwards and backwards.
Step 3: Print result
Based on the comparison, we print whether the string is a palindrome or not.
Alternative Approaches
using System; class Program { static bool IsPalindrome(string s) { int left = 0, right = s.Length - 1; while (left < right) { if (s[left] != s[right]) return false; left++; right--; } return true; } static void Main() { Console.Write("Enter a string: "); string input = Console.ReadLine(); if (IsPalindrome(input)) { Console.WriteLine($"{input} is a palindrome."); } else { Console.WriteLine($"{input} is not a palindrome."); } } }
using System; class Program { static void Main() { Console.Write("Enter a string: "); string input = Console.ReadLine(); string reversed = ""; for (int i = input.Length - 1; i >= 0; i--) { reversed += input[i]; } if (input == reversed) { Console.WriteLine($"{input} is a palindrome."); } else { Console.WriteLine($"{input} is not a palindrome."); } } }
Complexity: O(n) time, O(n) space
Time Complexity
Reversing the string takes O(n) time where n is the string length, and comparing two strings also takes O(n). Overall complexity is O(n).
Space Complexity
Creating a reversed string requires O(n) extra space. The two-pointer approach can reduce space to O(1).
Which Approach is Fastest?
The two-pointer approach is fastest in space as it avoids extra string creation, but using Reverse() is simpler and clear for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using string.Reverse() | O(n) | O(n) | Simplicity and readability |
| Two-pointer approach | O(n) | O(1) | Memory efficiency |
| Manual for loop reversal | O(n) | O(n) | Understanding string manipulation basics |
string.Reverse() with ToArray() to quickly reverse a string in C#.