Valid Palindrome IV — LeetCode 2330 Python Solution
MediumLeetCode PremiumTwo PointersString
- Problem
- #2330
- Pattern
- Two Pointers
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
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
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.