Problem Statement:
You are given a string S. The task is to determine if the string can be transformed into a palindrome by deleting at most one character.
Approach:
To determine if the string can be a palindrome after deleting at most one character, we can use a two-pointer technique. The key idea is to check the string from both ends towards the center and identify the first mismatch. When a mismatch is found, there are two possible ways to potentially fix the string:
- Skip the character at the left pointer.
- Skip the character at the right pointer.
If either of these modifications results in a valid palindrome, the original string can be considered a valid palindrome after deleting one character.
Step-by-Step Explanation:
-
Two-Pointer Technique:
- Use two pointers,
leftstarting at the beginning of the string andrightstarting at the end. - Move the
leftpointer forward and therightpointer backward towards the center, comparing the characters at each position.
- Use two pointers,
-
Handling Mismatch:
- If the characters at
leftandrightare the same, move both pointers closer to the center. - If the characters are different, check two scenarios:
- Skip the character at
leftand check if the remaining substring (fromleft + 1toright) is a palindrome. - Skip the character at
rightand check if the remaining substring (fromlefttoright - 1) is a palindrome.
- Skip the character at
- If the characters at
-
Checking Substring for Palindrome:
- Use a helper function
isPalindrometo check if a given substring (bounded byleftandrightindices) is a palindrome.
- Use a helper function
-
Return Result:
- If either scenario (skipping left or right) results in a palindrome, return
true. - If no mismatches are found during the initial comparison (i.e., the string is already a palindrome), return
true.
- If either scenario (skipping left or right) results in a palindrome, return
-
Edge Case:
- A single character string or an empty string is trivially a palindrome.
Complexity:
-
Time Complexity: The time complexity is
O(N), whereNis the length of the string. This is because each character is checked at most twice. -
Space Complexity: The space complexity is
O(1)since no additional space is required beyond a few variables.