You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
3
+
https://leetcode.com/problems/valid-palindrome
4
4
5
-
Given a string `s`, return `true` if it is a palindrome, or `false` otherwise.
5
+
## Description
6
+
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
7
+
8
+
Given a string `s`, return `true`*if it is a **palindrome**, or *`false`* otherwise.*
6
9
7
10
**Examples**
8
-
```text
11
+
12
+
```tex
9
13
Example 1:
10
14
Input: s = "A man, a plan, a canal: Panama"
11
15
Output: true
@@ -20,92 +24,84 @@ Example 3:
20
24
Input: s = " "
21
25
Output: true
22
26
Explanation: s is an empty string "" after removing non-alphanumeric characters.
23
-
An empty string is a palindrome.
27
+
Since an empty string reads the same forward and backward, it is a palindrome.
24
28
```
25
29
26
-
**Constraints:**
27
-
```text
28
-
1 <= s.length <= 2 * 10^5
29
-
s consists only of printable ASCII characters.
30
+
**Constraints**
31
+
```tex
32
+
- 1 <= s.length <= 2 * 10^5
33
+
- s consists only of printable ASCII characters
30
34
```
31
35
32
36
## Explanation
33
-
You're given a string `s`. Your task is to determine if it's a palindrome. A palindrome is a sequence that reads the same forwards and backwards. However, there are two special rules for this problem:
34
-
1. You should ignore all non-alphanumeric characters (like spaces, commas, colons, etc.).
35
-
2. You should treat uppercase and lowercase letters as the same (e.g., 'A' is the same as 'a').
36
-
37
-
So, "A man, a plan, a canal: Panama" should become "amanaplanacanalpanama" before checking if it's a palindrome.
38
37
39
38
### Strategy
40
-
You are given a string `s`.
41
-
The problem asks you to check if `s` is a palindrome after specific filtering and casing rules.
42
-
This is a string manipulation and two-pointer problem.
39
+
Let's restate the problem: You're given a string that may contain letters, numbers, spaces, and punctuation marks. You need to determine if it's a palindrome after cleaning it up (removing non-alphanumeric characters and converting to lowercase).
43
40
44
-
**Constraints:**
45
-
*`1 <= s.length <= 2 * 10^5`: The string can be quite long, so an O(n) solution is preferred. O(n log n) might also pass, but O(n^2) would be too slow.
46
-
*`s consists only of printable ASCII characters`: This simplifies character handling, no complex encodings.
41
+
This is a **two-pointer problem** that involves string preprocessing and then checking for palindrome properties.
47
42
48
-
The most robust and efficient strategy involves processing the string to meet the palindrome rules and then applying a two-pointer approach. You can either pre-process the entire string first, or filter characters on the fly while comparing. The "on-the-fly" method is often slightly more memory-efficient as it doesn't create a new full string immediately, but both are O(N) time and O(N) or O(1) space (depending on how you count auxiliary space for the cleaned string). The "on-the-fly" method often has better constant factors for space.
43
+
**What is given?** A string that may contain various characters including letters, numbers, spaces, and punctuation.
49
44
50
-
Let's focus on the "Two Pointers with On-the-Fly Filtering" strategy, as it's generally preferred for interviews due to its space efficiency and direct manipulation of the original string.
45
+
**What is being asked?** Determine if the cleaned string (only alphanumeric characters, all lowercase) is a palindrome.
51
46
52
-
**Decomposition:**
53
-
1. Initialize two pointers, `left` at the beginning of the string and `right` at the end.
54
-
2. While `left` is less than `right`:
55
-
a. Move `left` inwards until it points to an alphanumeric character.
56
-
b. Move `right` inwards until it points to an alphanumeric character.
57
-
c. If `left` is still less than `right` (meaning both found valid characters):
58
-
i. Compare the characters at `left` and `right`, ignoring case.
59
-
ii. If they don't match, return `false` (not a palindrome).
60
-
iii. If they match, move `left` one step right and `right` one step left.
61
-
d. If `left` becomes `right` or `left` crosses `right`, the loop ends.
62
-
3. If the loop completes, it means all compared alphanumeric characters matched, so return `true` (it's a palindrome).
47
+
**Constraints:** The string can be up to 200,000 characters long and contains only printable ASCII characters.
63
48
64
-
### Steps
65
-
Let's use the example `s = "A man, a plan, a canal: Panama"`
49
+
**Edge cases:**
50
+
- Empty string (should return true)
51
+
- String with only non-alphanumeric characters (should return true)
52
+
- Single character (should return true)
53
+
- String with mixed case and punctuation
54
+
55
+
**High-level approach:**
56
+
The solution involves two main steps:
57
+
1.**Preprocessing**: Clean the string by removing non-alphanumeric characters and converting to lowercase
58
+
2.**Palindrome check**: Use two pointers to check if the cleaned string reads the same forward and backward
...This process repeats. Non-alphanumeric characters (spaces, commas, colons) will cause one of the inner `while` loops to advance a pointer. For example, if `s[left]` is a space, `left` will increment until it finds an alphanumeric character. The same happens for `right` moving inwards.
92
+
**Step 5: Continue until pointers meet**
93
+
- Continue this process, comparing characters at both ends
94
+
- Move pointers inward after each successful comparison
95
+
- Stop when `left >= right`
97
96
98
-
Eventually, if `s = "A man, a plan, a canal: Panama"`, all corresponding alphanumeric characters will match. The pointers will cross or meet (`left >= right`). When `left` is no longer less than `right`, the `while left < right` loop terminates.
97
+
**Step 6: Check result**
98
+
- If we reach the middle without finding a mismatch, it's a palindrome
99
+
- In this case, all characters match, so return `true`
99
100
100
-
At this point, since no mismatches were found, the function returns `true`.
101
+
**Why this works:**
102
+
A palindrome reads the same forward and backward. By using two pointers that start at opposite ends and move inward, we can efficiently check this property. If at any point the characters don't match, we know it's not a palindrome. If we reach the middle with all characters matching, it must be a palindrome.
> **Note:** The key insight is that we don't need to create a new cleaned string. We can process the original string character by character, skipping non-alphanumeric characters and converting case on-the-fly.
110
105
111
-
This approach is efficient because it processes each character at most a constant number of times (once by `left`, once by `right`). So, time complexity is O(n). Space complexity is O(1) because you're only using a couple of pointers and not creating new large data structures.
106
+
**Time Complexity:** O(n) - we process each character at most once
107
+
**Space Complexity:** O(1) - we only use a constant amount of extra space for the pointers
0 commit comments