I had come across a similar question during my olympiad days and to adapt that question to this case was extremely tough. I tried a lot of methods to solve this. Initially tried brute forcing my way through this problem but with a nudge in the right direction from a friend I implemented a two pointer method in this problem. Uploading it in polygon was a real tough thing to do, I got stuck on the checker part of this question where I had tons of failed invocations but in the end it all worked out. The problem is a real beauty. It looks really simple at first but when you delve deep into it, you find it to be a great problem.
Link to Problem on Polygon : https://polygon.codeforces.com/p7aoui9/notdilbarsl/whimsical-sorter