wasAsked.

Write palindrome code?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · C#

Community answers

Posted by wasAsked editorial collection

A palindrome reads the same forwards and backwards, such as "madam" or "racecar". Two-pointer approach — efficient, O(n) time, O(1) extra space: public static bool IsPalindrome(string? text) { if (string.IsNullOrEmpty(text)) return false; // decide and state your rule for empty input int left = 0, right = text.Length - 1; while (left < right) { if (text[left] != text[right]) return false; left++; right--; } return true; } Ignoring case, spaces and punctuation ("A man, a plan, a canal: Panama"): public static bool IsPalindromeIgnoringNonLetters(string text) { int left = 0, right = text.Length - 1; while (left < right) { if (!char.IsLetterOrDigit(text[left])) { left++; continue; } if (!char.IsLetterOrDigit(text[right])) { right--; continue; } if (char.ToLowerInvariant(text[left]) != char.ToLowerInvariant(text[right])) return false; left++; right--; } return true; } Short LINQ version (readable, but allocates): public static bool IsPalindromeLinq(string text) { var cleaned = text.Where(char.IsLetterOrDigit).Select(char.ToLowerInvariant).ToArray(); return cleaned.SequenceEqual(cleaned.Reverse()); } Number palindrome (without converting to a string): public static bool IsPalindrome(int number) { if (number < 0) return false; int original = number, reversed = 0; while (number > 0) { reversed = reversed * 10 + number % 10; number /= 10; } return original == reversed; } Tests to mention IsPalindrome("madam") is true, "hello" is false, a single character is true, "Madam" depends on the case rule, the Panama sentence is true with the cleaning version, and 121 is true while 123 is false. Discussion points: the two-pointer version avoids creating reversed strings; string.Reverse creates allocations; for user-entered text, be explicit about case sensitivity and which characters you ignore; for full Unicode correctness (combining characters, emoji), compare text elements using StringInfo rather than single chars.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics