Is there a reason your code doesn't work if the keys of these sets aren't ordered? That seems to me like something that should be refactored out, rather than catered to, unless there's some design subtlety I'm missing here.