Problem of the day
Ninja’s friend challenged him with a trick question. He gave him a string ‘S’ and asked him if it is possible to make this string palindrome by deleting one character from the string. Can you help the ninja to solve this problem?
You are given a string ‘S’ of size ‘N’.You have to determine whether it is possible to make the string palindrome by deleting at most one character.
For ExampleIf the string is ‘AZBCDCBA’, the answer will be YES as we can delete the character ‘Z’ and the remaining string is a palindrome.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case has a single integer ‘N’ denoting the length of string ‘S’.
The second line of each test case contains the string ‘S’.
Output Format:
For each test case, print ‘YES’ or ‘NO’ as is it possible to make the string palindrome by deleting at most one character.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5.
Time limit: 1 sec
2
8
AZBCDCBA
3
ABA
YES
YES
For the first test case,
If we remove the letter ‘Z’ from the string , the remaining string ‘ABCDCBA’ is palindromic.Hence, the answer is YES.
For the second test case:
The given string is already palindromic. Hence, the answer is YES.
2
6
ROSSVR
6
VWHGWV
NO
YES
Try out to find the character which does not match the condition of the palindrome.
In this approach, we will first define a function IS_PALINDROME(‘S’, i,j), which returns whether the substring from i to j is palindrome or not. Now, we will take two pointers, i and j, and iterate the string using these pointers, one from the front and another from the back, when we find a condition that S[i] is not equal to S[j]. We have two choices:
Delete ith character. If substring from i+1 to j is a palindrome, the answer is true.
Delete jth character. If substring from i to j-1 is a palindrome, the answer is true.
If neither is true, we cant make this string palindrome. So return false.
If we never encounter the above condition, it means that our string is already palindrome. So, return simply true.
Algorithm:
O(N), where ‘N’ is the length of the string.
In this approach, we are iterating all characters of strings using two pointers. Hence, the overall time complexity is O(N).
O(1).
In this approach, we are using constant space. Hence, the overall space complexity is O(1).