- LeetCode Problem: Valid Palindrome (LeetCode 125 - Easy)
- Problem Statement: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. The string may contain non-alphanumeric characters which are to be ignored.
- For example:
- Input: "A man, a plan, a canal: Panama"
- Output: True
- Explanation: Ignoring cases and non-alphanumeric characters, the string is "AmanaplanacanalPanama", which is a palindrome.
- Potential Interview Questions:
- Can the input string be empty?
- How should we handle case sensitivity?
- How should we treat special characters or spaces?
- An empty string is considered a palindrome.
- A string with one character is a palindrome.
- A string with spaces or punctuation marks only can also be considered a palindrome.
- Two Pointers: One from start and another from the end, ignore the non-alphanumeric characters, and compare the characters at two pointers.
- Use two pointers, one at the start of the string and one at the end.
- Ignore the non-alphanumeric characters.
- Compare the characters at the two pointers. If they are not the same, return False.
- Move the pointers towards each other and repeat until the pointers meet.
class Solution:
? ? def isPalindrome(self, s: str) -> bool:
? ? ? ? left, right = 0, len(s) - 1
? ? ? ??
? ? ? ? while left < right:
? ? ? ? ? ? while left < right and not s[left].isalnum():
? ? ? ? ? ? ? ? left += 1
? ? ? ? ? ? while left < right and not s[right].isalnum():
? ? ? ? ? ? ? ? right -= 1
? ? ? ? ? ? ? ??
? ? ? ? ? ? if s[left].lower() != s[right].lower():
? ? ? ? ? ? ? ? return False
? ? ? ? ? ??
? ? ? ? ? ? left, right = left + 1, right - 1
? ? ? ??
? ? ? ? return True
This code uses the two-pointer approach to solve the problem. The pointers left and right are initially at the start and end of the string, respectively. The while loop continues until the two pointers meet. Inside the loop, we skip over any non-alphanumeric characters. If the characters at the pointers are not the same (ignoring case), we return False. If we finish the loop without finding a mismatch, we return True, indicating the string is a palindrome.
Solution Explanation for a Non-Technical Person:
- Think of a palindrome as a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization.
- An example would be "Able was I ere I saw Elba". If we ignore the spaces and the capitalization, we see that it reads the same forwards and backwards.
- To solve this problem, we start at the beginning and end of the phrase and move towards the middle, comparing each pair of characters.
- If we find a pair of characters that are not the same, then we know it's not a palindrome and we can stop.
- If we make it all the way to the middle without finding any differences, then it's a palindrome.
Detailed Code Explanation:
- We start by initializing two pointers, left at the start of the string, and right at the end.
- We enter a loop that continues until the left and right pointers meet in the middle of the string.
- Inside the loop, we have two inner loops that skip over any characters in the string that are not alphanumeric (i.e., letters or numbers).
- We then compare the characters at the left and right pointers (ignoring any difference in case). If they are not the same, we immediately return False, because this means the string is not a palindrome.
- If the characters are the same, we move the left pointer one step to the right and the right pointer one step to the left, and continue the loop.
- If we finish the loop without finding any pairs of characters that are different, this means we have a palindrome, so we return True.
- The pattern in this problem is called the "two-pointer" technique.
- In this pattern, we typically have two pointers that start at different positions in a list or string (commonly at the beginning and end) and move towards each other.
- As the pointers move, we check certain conditions at each step.
- This pattern is commonly used in problems involving arrays or strings, especially when we need to compare elements from the start and end, or when we want to avoid using extra space.
- The time complexity for this problem is O(n), where n is the length of the string. This is because in the worst-case scenario, we have to iterate through the entire string once. The space complexity is O(1), because we are not using any additional space that scales with the input size. We only use a constant amount of space to store our two pointers.
- Remember the two-pointer technique, where you start pointers at the beginning and end of a string or array and move them towards each other. This is a common pattern for many problems.
- When dealing with strings, keep in mind the built-in Python methods such as isalnum() and lower() which check if a character is alphanumeric and convert a character to lower case, respectively.
- In Python, the '==' operator is case-sensitive. So, always convert to the same case before comparison.
Line-by-Line Code Explanation:
- Let's take the string s = "A man, a plan, a canal: Panama" as an example.
- The pointers left and right start at positions 0 and length of the string - 1, respectively.
- Inside the while loop, the code checks if the characters at the left and right positions are alphanumeric. If not, it increments left or decrements right as necessary.
- Then it checks if the characters at left and right, converted to lower case, are equal. If not, it returns False.
- If they are equal, it moves left one step right and right one step left.
- If left becomes equal to or greater than right, it means we've checked all the relevant characters, and the function returns True.
- str.isalnum(): This string method in Python checks if all the characters of a string are alphanumeric (a-z, A-Z, 0-9).
- str.lower(): This string method converts all uppercase characters in a string into lowercase characters and returns the lowercased string.
- while loop: It is used when we want to repeat a block of code an unknown number of times until a specific condition is met.
- Comparison operators (==, !=): These operators are used to compare the values on either side of them and decide the relation among them. Here, we're using == to check if two characters are the same and != to check if left has passed right.
- LeetCode 125 - Valid Palindrome II: Difficulty - Easy:In this problem, you are asked to determine whether a given string can become a palindrome after removing at most one character.
- LeetCode 680 - Reverse String: Difficulty - Easy:The task is to reverse a string. You could solve this using the two-pointer technique.
- LeetCode 344 - Reverse String II: Difficulty - Easy:In this problem, you are given a string and an integer k. You need to reverse the first k characters for every 2k characters counting from the start of the string.
- LeetCode 5 - Longest Palindromic Substring: Difficulty - Medium: Here, you are required to find the longest substring which is also a palindrome.
- LeetCode 516 - Longest Palindromic Subsequence: Difficulty - Medium: This problem asks you to find the longest subsequence of a string that is also a palindrome.
- LeetCode 131 - Palindrome Partitioning: Difficulty - Medium: In this problem, you have to partition a string such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of the string.
The next problem in this series is