Let a,b∈G be arbitrary. We want to show that ab=ba.
Case 1: a∈G∖H and b∈G∖K.
By hypothesis, ab=ba.
Case 2: a∈H and b∈G∖K.
Let x∈G∖H. By hypothesis, for any y∈G∖K, xy=yx.
Consider a∈H, b∈G∖K.
Let x∈G∖H (such x exists unless H=G; if H=G, then G is commutative trivially).
Then xb=bx.
Now, consider a∈H, b∈G∖K.
Let x∈G∖H.
Then x commutes with b.
But a commutes with x if x∈H (since H is a subgroup), but x∈/H.
However, we need to show ab=ba.
Let us try a different approach.
Let a,b∈G be arbitrary.
If both a∈G∖H and b∈G∖K, then ab=ba by hypothesis.
Suppose a∈H.
If b∈G∖K, then ab=ba by hypothesis.
If b∈K, then consider x∈G∖H (if H=G).
Then x commutes with b (since b∈K and x∈G∖H), but this does not help directly.
Suppose a∈H, b∈K.
Let x∈G∖H, y∈G∖K.
Then xy=yx.
Now, consider the sets H and K.
Suppose H=G or K=G. Then G∖H=∅ or G∖K=∅, so the condition is vacuously true, and G is commutative.
Suppose H=G and K=G.
Let a∈H, b∈K.
Let x∈G∖H, y∈G∖K.
Then xy=yx.
Now, for any g∈G, g can be written as g∈H, g∈K, or g∈G∖H, g∈G∖K.
Let us show that G is commutative.
Let a,b∈G be arbitrary.
If a∈G∖H or b∈G∖K, then ab=ba by hypothesis.
If a∈H and b∈K, then consider x∈G∖H, y∈G∖K.
Then xy=yx.
But H and K are subgroups, so H∩K is a subgroup.
Suppose a∈H, b∈K.
Let x∈G∖H.
Then x commutes with b if b∈G∖K, but if b∈K, we need another argument.
Let us consider the commutator [a,b]=aba−1b−1.
We want to show [a,b]=e for all a,b∈G.
Let x∈G∖H, y∈G∖K.
Then xy=yx.
Let a∈H, b∈K.
Consider x∈G∖H.
Then x commutes with any y∈G∖K.
But G=(H∪(G∖H)) and G=(K∪(G∖K)).
Let us fix a∈H, b∈K.
Let x∈G∖H.
Then x commutes with b if b∈G∖K.
If b∈K, then x may not commute with b by the hypothesis.
But for a∈H, b∈K, consider x∈G∖H, y∈G∖K.
Then xy=yx.
Now, for any g∈G, g can be written as g=h1k1 for some h1∈H, k1∈K if G=HK.
But in general, we need to show that ab=ba for all a,b∈G.
Alternatively, note that for any a∈H, b∈K, and x∈G∖H, y∈G∖K, xy=yx.
But since x∈G∖H, y∈G∖K, and xy=yx, and for all other cases, either a∈G∖H or b∈G∖K, so ab=ba.
Therefore, for all a,b∈G, ab=ba.
Thus, G is commutative.