709865. Min Chars to Add for Palindrome
Min Chars to Add for Palindrome
Summary
Given a string, find the minimum number of characters that need to be added at the front to make it a palindrome. A palindrome is a string that reads the same backward as forward.
This problem involves manipulating strings and checking if they are palindromes. The key concept involved is the construction of a palindrome by adding characters at the front.
Detailed Explanation
To solve this problem, we can use a two-pointer approach. Initialize two pointers, left and right, to the end of the string. Move them towards each other until they meet in the middle (since the string is already a palindrome).
For each step, check if the characters at the left and right positions are the same. If they are not, add the character at the right position to the front of the string and decrement right. Continue this process until left and right meet in the middle.
Here's a step-by-step breakdown:
- Initialize
leftandrightpointers to the end of the string. - While
leftandrightdo not meet:- Check if the characters at positions
leftandrightare the same. - If they are not, add the character at position
rightto the front of the string. - Decrement
right.
- Check if the characters at positions
- Return the number of characters added.
Time complexity: O(n), where n is the length of the string. Space complexity: O(1), since we only use a constant amount of space.
Optimized Solutions
Java
public int minCharsToMakePalindrome(String s) {
int left = s.length() - 1;
int right = s.length() - 1;
int count = 0;
while (left >= 0 && right < s.length()) {
if (s.charAt(left) == s.charAt(right)) {
left--;
right--;
} else {
count++;
right--;
}
}
return count;
}