Problem 573408 · medium · Phase 05 Advanced Algorithms & Graphs

Two Socks Without a Partner

bit manipulation · XOR · partitioning

A laundry basket holds socks with pattern ids socks. Every pattern appears exactly twice except two different patterns that appear once each. Return those two ids in increasing order as a list. Aim for O(1) extra space.

Examples

Input:  socks = [4, 1, 2, 1, 2, 7]
Output: [4, 7]
Input:  socks = [-3, 0]
Output: [-3, 0]

Constraints

  • 2 <= len(socks) <= 10**5 + 2, -2**31 <= socks[i] < 2**31.
  • Target complexity: O(n) time, O(1) extra space.

Goals

  • Use XOR to cancel every pair
  • Isolate one bit where the two unpaired values differ
  • Split the values into two groups using that bit
Starting Python…