A simple solution using binary search tree and Breadth first search. No group theory. No Lehmer codes.