Practice › Strings
Check Palindrome
Easy · Strings · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
A palindrome reads the same forwards and backwards. Print YES if the string s is a palindrome, otherwise NO.
Input
One line with the string s (lowercase letters only).
Output
YES or NO.
Constraints
- 1 ≤ |s| ≤ 10^5
Example 1
Input
madam
Output
YES
Example 2
Input
codify
Output
NO
Hints
- Compare the first character with the last, the second with the second-last, and so on.
- As soon as one pair differs, the answer is NO.
Approach
Move two pointers inward from both ends. If any s[i] != s[j], it isn't a palindrome. If the pointers meet without a mismatch, it is. No reversed copy is needed.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
bool ok = true;
for (int i = 0, j = (int)s.size() - 1; i < j; i++, j--)
if (s[i] != s[j]) { ok = false; break; }
cout << (ok ? "YES" : "NO") << "\n";
return 0;
}Python solution
s = input().strip()
print("YES" if s == s[::-1] else "NO")Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
boolean ok = true;
for (int i = 0, j = s.length() - 1; i < j; i++, j--)
if (s.charAt(i) != s.charAt(j)) { ok = false; break; }
System.out.println(ok ? "YES" : "NO");
}
}