MediumNo. 2330LeetCode Premium
Valid Palindrome IV — LeetCode 2330 Python Solution
- Pattern
- Two Pointers
- Topics
- Two Pointers, String
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed string s consisting of only lowercase English letters. In one operation, you can change any character of s to any other character.
Example
- Input
- s = "abcdba"
- Output
- true
- Explanation
- One way to make s a palindrome using 1 operation is:
Python solution
class Solution:
def makePalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
cnt = 0
while i < j:
cnt += s[i] != s[j]
i, j = i + 1, j - 1
return cnt <= 2Complexity
- Time
- O(n)
- Space · auxiliary
- O(1)
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 2330. Valid Palindrome IV is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0125 | Valid Palindrome | Easy |
| 2337 | Move Pieces to Obtain a String | Medium |
| 0005 | Longest Palindromic Substring | Medium |
| 0028 | Find the Index of the First Occurrence in a String | Easy |
| 0151 | Reverse Words in a String | Medium |
| 0165 | Compare Version Numbers | Medium |
Frequently asked questions
- How hard is LeetCode 2330. Valid Palindrome IV?
LeetCode 2330. Valid Palindrome IV is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2330. Valid Palindrome IV?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2330. Valid Palindrome IV?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2330. Valid Palindrome IV cover?
LeetCode 2330. Valid Palindrome IV is tagged Two Pointers and String on LeetCode.
- Is LeetCode 2330. Valid Palindrome IV a premium problem?
Yes. LeetCode 2330. Valid Palindrome IV is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.