Wow so proud of myself this seemed impossible when i started
I fully blame betseg for this, we had an hour of discussion whether you could make this O(n). Turns out, you can.