Given a string
Output: true
Output: true
Explanation: You could delete the character 'c' or 'b'.
Output: false
Constraints:
- 1 <= s.length <= 105
-
s consists of lowercase English letters.
Contents
Solution 1 - Using two pointers approach
In this approach, we will use two pointers
Implementation steps:
-
We will first initialize two variables
start = 0 , andend = s.length() -1 , both points to left and right ends of the strings , and two more variables to count characters removed on left side and right side of the stringcharsDeletedOnLeft andcharsDeletedOnRight . -
While
start andend do not intersect each other, read the characters and check the followng:-
If characters match on both sides : Since characters on both ends are same, increment
start and decrementend . -
If characters don't match on both sides :
-
First, try removing character on right side, i.e. decrement
end and incrementcharsDeletedOnRight by 1. -
If removing right character already tried and still characters don't match, try removing character on left side,
i.e. increment
start and incrementcharsDeletedOnLeft by 1, but we also need to incrementend , since we have already tried removing right side character, so we have to move it back to where it was. -
If both of the above options are tried, i.e. removing a left character as well as a right character, and the characters dont match, then return
false .
-
First, try removing character on right side, i.e. decrement
-
If characters match on both sides : Since characters on both ends are same, increment
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at