#680

Valid Palindrome II

Easy
Two PointersStringGreedyTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Using a two-pointer technique, we can check for palindromic properties while allowing for one character to be skipped. This is more efficient as it avoids creating multiple substrings.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, left at the start and right at the end of the string.
  2. 2Step 2: While left is less than right, check if the characters at these pointers are equal.
  3. 3Step 3: If they are not equal, check the two possibilities: skip the left character or skip the right character.
  4. 4Step 4: If either possibility results in a palindrome, return true. If the loop completes, return true.
solution.py18 lines
1# Full working Python code
2
3def valid_palindrome(s):
4    def is_palindrome_range(left, right):
5        while left < right:
6            if s[left] != s[right]:
7                return False
8            left += 1
9            right -= 1
10        return True
11
12    left, right = 0, len(s) - 1
13    while left < right:
14        if s[left] != s[right]:
15            return is_palindrome_range(left + 1, right) or is_palindrome_range(left, right - 1)
16        left += 1
17        right -= 1
18    return True

Complexity note: The optimal solution runs in O(n) time because we only traverse the string once with two pointers, and the space complexity is O(1) since we are not using any additional data structures.

  • 1Using two pointers is efficient for palindrome checks.
  • 2Skipping characters can help in validating near-palindromes.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.