Your code fails for the test case
I couldn’t rectify your code without altering your approach but this is where you code goes wrong.
The map that you’re creating maps input as follows: aaBCCeBdAaeCc
Now the letters in bold would hold their indexes in your final map and as you can see Ce at 4,5 can be replace with eC at 10,11 but your loop fails to do so
Hence, you get 9 instead of 7
You might wanna change your approach instead.
Do share your code once it’s accepted.
Hope this helps.