Problem Statement
Given a string containing only lowercase English letters, determine the minimum length of a contiguous substring that can be removed such that the remaining characters can be rearranged to form a palindrome.
Examples
Example 1:
Input: "abca"
Output: 1
Explanation: Removing the substring “b” leaves “aca”, which can be rearranged into the palindrome "aca".
Example 2:
Input: "abbc"
Output: 1
Explanation: Removing the substring “a” or “c” leaves “bbc” or “abb”, either of which can be rearranged into a palindrome.
Example 3:
Input: "abcd"
Output: 3
Explanation: Removing any three characters leaves a single character, which is trivially a palindrome.
Example 4:
Input: "aabbcc"
Output: 0
Explanation: The string already satisfies the condition, as it can be rearranged into the palindrome “abccba”.
Challenge
Can you come up with a linear time solution?
Hi Kuai, Really good question!
I am sharing the solution here
1) have a hashmap
2)for this hashmap,check for the odd
3)return the oddcount-1 if its more than 0 else return 0
function checkPalindrome(str){
let count=0
let map=new Map()
for(let i=0;i<str.length;i++)
{
map.set(str[i],(map.get(str[i])||0)+1)
}
let oddCount=0
for(let [key,value] of map)
{
if(value%2!=0)
{
oddCount++
}
}
return oddCount>0?oddCount-1:0
}
Hi Kuai Great question! This problem is a fun one because it combines string manipulation with palindrome properties, which are always interesting to think about. Here's how I'd approach it,
The goal is to remove the smallest possible contiguous substring so that the remaining string can be rearranged into a palindrome. For a string to be rearranged into a palindrome, there can be at most one character with an odd frequency (for odd-length strings). This is a key observation!
I’d start by checking if the entire string can already be rearranged into a palindrome. If it can, then no removal is needed, and the answer is 0. If not, the challenge becomes finding the smallest substring to remove that makes the rest of the string palindromic.
We can use a two-pointer technique here:
Start with two pointers: one at the beginning (left) and one at the end (right).
If the characters at both pointers are the same, great! Move both pointers inward.
If the characters are different, you have two options:
Remove the character at the left pointer and check if the remaining string can form a palindrome.
Or remove the character at the right pointer and check again.
If either of these works, we return 1 because we only need to remove one character. If neither works, then we might need to remove two characters, so we return 2.