https://usaco.guide/problems/cses-3175-beautiful-permutation-ii/solution
I solved Beautiful Permutations II in Python, then looked at the internal solution in C++, which is a lot simpler than what I did. I notice it depends on a tree set, so that’s not available in Python (is that right?). I tried to implement the internal solution in Java as an experiment, using a TreeSet<Integer>, and got an concurrent modification exception. How does the C++ version avoid this? The issue is that while backtracking you are looping over elements of the set, removing them and reinserting them multiple times in each recursive call.
What I did in Python was use a pattern that I figured would be correct for all but the trailing 10 or so numbers, then backtrack search on the last 10 numbers, which was slow but feasible for only 10 numbers.