Rewrite mergeKeySets to be O(n) instead of O(n^3)