#125

Valid Palindrome

Easy
Two PointersStringTwo 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)

The optimal approach uses two pointers to check characters from both ends of the string towards the center. This avoids the need for extra space for a reversed string and is more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, one at the start and one at the end of the string.
  2. 2Step 2: Move the pointers towards the center, skipping non-alphanumeric characters.
  3. 3Step 3: Compare the characters at both pointers. If they are not the same, return false. If they are the same, continue until the pointers meet.
  4. 4Step 4: If all characters match, return true.
solution.py13 lines
1# Full working Python code
2def isPalindrome(s):
3    left, right = 0, len(s) - 1
4    while left < right:
5        while left < right and not s[left].isalnum():
6            left += 1
7        while left < right and not s[right].isalnum():
8            right -= 1
9        if s[left].lower() != s[right].lower():
10            return False
11        left += 1
12        right -= 1
13    return True

Complexity note: The time complexity is O(n) because we only traverse the string once with two pointers. The space complexity is O(1) since we are not using any additional data structures that grow with input size.

  • 1Cleaning the string is essential for accurate palindrome checking.
  • 2Using two pointers is an efficient way to compare characters without extra space.

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