Practice › Strings
Valid Palindrome Ignoring Symbols
Easy · Strings · Asked at Meta, Amazon, Microsoft, TCS, Infosys
Consider only the letters and digits of the line, and ignore the difference between upper and lower case. Print YES if what remains reads the same forwards and backwards, otherwise NO. (If nothing remains, the answer is YES.)
Input
A single line of text (letters, digits, spaces and punctuation).
Output
YES or NO.
Constraints
- 1 ≤ length ≤ 2 × 10^5
Two pointers: skip characters that are not letters or digits, compare the rest in lower case, and move inward.
Example 1
Input
A man, a plan, a canal: Panama
Output
YES
Example 2
Input
race a car
Output
NO
Hints
- Read the whole line — it contains spaces.
- Skip anything that is not a letter or digit.
- Compare the remaining characters in lower case from both ends.
Approach
Use two pointers. Move i forward and j backward past characters that are not alphanumeric; then compare tolower(s[i]) with tolower(s[j]). A mismatch means NO. If the pointers meet, the answer is YES — this also covers a line with no letters or digits at all.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
getline(cin, s);
int i = 0, j = (int) s.size() - 1;
while (i < j) {
if (!isalnum((unsigned char) s[i])) i++;
else if (!isalnum((unsigned char) s[j])) j--;
else if (tolower(s[i]) != tolower(s[j])) {
cout << "NO\n";
return 0;
} else {
i++;
j--;
}
}
cout << "YES\n";
return 0;
}Python solution
import sys
s = sys.stdin.readline().rstrip("\r\n")
t = [c.lower() for c in s if c.isascii() and c.isalnum()]
print("YES" if t == t[::-1] else "NO")Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
int i = 0, j = s.length() - 1;
while (i < j) {
char a = s.charAt(i), b = s.charAt(j);
if (!Character.isLetterOrDigit(a)) i++;
else if (!Character.isLetterOrDigit(b)) j--;
else if (Character.toLowerCase(a) != Character.toLowerCase(b)) {
System.out.println("NO");
return;
} else {
i++;
j--;
}
}
System.out.println("YES");
}
}Solve Valid Palindrome Ignoring Symbols online · All practice problems