The problem asks whether a given string s
can be transformed into a palindrome with at most two character changes. The optimal approach uses a two-pointer technique for efficiency.
Algorithm:
Two Pointers: Initialize two pointers, i
and j
, pointing to the beginning and end of the string, respectively.
Iteration and Comparison: Iterate while i
is less than j
. In each iteration, compare s[i]
and s[j]
.
Mismatch Count: If s[i]
and s[j]
are different, increment a counter cnt
. This counter tracks the number of mismatches.
Pointer Movement: Move i
one step to the right and j
one step to the left.
Result: After the loop, if cnt
is less than or equal to 2, it means at most two character changes are needed to make the string a palindrome, so return true
. Otherwise, return false
.
Time Complexity Analysis:
The algorithm iterates through the string once using two pointers. Therefore, the time complexity is O(n), where n is the length of the string.
Space Complexity Analysis:
The algorithm uses a constant amount of extra space to store the counter cnt
and pointers i
and j
. Thus, the space complexity is O(1).
The code implementations below follow the algorithm described above. They all achieve the same functionality with minor syntax variations.
Python3:
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 <= 2
Java:
class Solution {
public boolean makePalindrome(String s) {
int cnt = 0;
int i = 0, j = s.length() - 1;
for (; i < j; ++i, --j) {
if (s.charAt(i) != s.charAt(j)) {
++cnt;
}
}
return cnt <= 2;
}
}
C++:
class Solution {
public:
bool makePalindrome(string s) {
int cnt = 0;
int i = 0, j = s.size() - 1;
for (; i < j; ++i, --j) {
cnt += s[i] != s[j];
}
return cnt <= 2;
}
};
Go:
func makePalindrome(s string) bool {
cnt := 0
i, j := 0, len(s)-1
for ; i < j; i, j = i+1, j-1 {
if s[i] != s[j] {
cnt++
}
}
return cnt <= 2
}
TypeScript:
function makePalindrome(s: string): boolean {
let cnt = 0;
let i = 0;
let j = s.length - 1;
for (; i < j; ++i, --j) {
if (s[i] !== s[j]) {
++cnt;
}
}
return cnt <= 2;
}
All these code snippets have the same time and space complexity as analyzed above. They efficiently solve the problem by directly checking the number of character mismatches needed for palindromic transformation.