Valid Palindrome in Python and Java
In this tutorial, we will learn LeetCode #125: Valid Palindrome in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Valid Palindrome Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use two pointers because it gives a clean and optimized solution.
Example input: s = "No lemon, no melon" Expected result: Output: true Explanation: Ignoring spaces and punctuation, it is a palindrome.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: s = "No lemon, no melon" Approach: two pointers We update variables step by step until we reach: Output: true
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why two pointers is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. s = "No lemon, no melon" We will solve it using two pointers. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: true Why? Ignoring spaces and punctuation, it is a palindrome.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: true
Example 1
Input: s = "No lemon, no melon" Output: Output: true Explanation: Ignoring spaces and punctuation, it is a palindrome.
Example 2
Input: s = "Was it a car or a cat I saw" Output: true Explanation: After ignoring spaces and case, it reads the same.
Python Code
Here is the complete Python solution for LeetCode #125.
class PalindromeValidator:
def is_palindrome(self, text):
left = 0
right = len(text) - 1
while left < right:
while left < right and not text[left].isalnum():
left += 1
while left < right and not text[right].isalnum():
right -= 1
if text[left].lower() != text[right].lower():
return False
left += 1
right -= 1
return True
validator = PalindromeValidator()
print(validator.is_palindrome("No lemon, no melon")) # Output: True
print(validator.is_palindrome("hello world")) # Output: FalseJava Code
Here is the complete Java solution for LeetCode #125.
class PalindromeValidator {
public boolean isPalindrome(String text) {
int left = 0;
int right = text.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(text.charAt(left))) {
left++;
}
while (left < right && !Character.isLetterOrDigit(text.charAt(right))) {
right--;
}
if (Character.toLowerCase(text.charAt(left)) != Character.toLowerCase(text.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
PalindromeValidator validator = new PalindromeValidator();
System.out.println(validator.isPalindrome("No lemon, no melon")); // true
System.out.println(validator.isPalindrome("hello world")); // false
}
}Time and Space Complexity
Time Complexity: O(n log n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #125: Valid Palindrome becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.