Discussion about this post

User's avatar
Sneha Priyadarshan's avatar

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

}

Expand full comment
Aditi Deshpande's avatar

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.

Expand full comment
2 more comments...

No posts