Here’s the problem Statement

I understood the question but can’t figure out how to implement it through code. I did read the editorial but it seems quiet complicated.

If anyone can provide a simple and clear implementation of this problem, then that would be really helpful.

The editorial says that it needs bitmasks, but how do I use it here?

Thanks in advance.