I came across this problem a while back. After thinking and implementing different approaches for this case, I still can't find the best one. My recent approach for this is really heavy to implement. I wonder what approach you guys will think to solve this problem and let's see if our idea matches!
Problem link: Here!