Exclusive Items

Exclusive Items

Given two slices of integers, return the values that appear in exactly one of them (in the first but not the second, or the second but not the first), with no duplicates, sorted ascending. This is the symmetric difference of the two sets.

exclusiveItems(a, b)

Input format: a | b. Output the exclusive values, sorted, space-separated (empty line if none).

Examples

exclusiveItems([]int{1, 2, 3}, []int{2, 3, 4})  // → [1, 4]
exclusiveItems([]int{1, 2}, []int{1, 2})        // → []
exclusiveItems([]int{5}, []int{6})              // → [5, 6]

Walkthrough

Thinking it through

This is the mirror image of the shared-elements problem: instead of values in both lists, you want values in exactly one. That's the symmetric difference — everything in one set or the other, but not both.

Breaking the problem into two symmetric halves

A value belongs in the answer if it's in the first list but missing from the second, or in the second but missing from the first. Both are membership questions, so reach for hash sets again: membership checks against a set are constant-time, while scanning a raw list is linear — and you'd be repeating that scan.

Building the approach

  1. Convert both lists into sets — this drops duplicates within each list for free, which is exactly what "no duplicates in the output" needs.
  2. Walk the first set; for each value, if it's absent from the second set, include it.
  3. Walk the second set; for each value, if it's absent from the first set, include it.
  4. Combine both groups and sort, since neither pass guarantees any order.

Why doing it in two separate passes is fine (and simple)

The two checks — "in first, not second" and "in second, not first" — can never both be true for the same value, so there's no risk of double-counting by running them as two independent passes.

Why this is efficient

Building both sets costs time proportional to the combined list sizes. Each pass costs time proportional to the set being walked, with constant-time lookups against the other. Total work stays linear in the combined input size, versus a brute-force comparison of every element against every other element, which costs time proportional to the product of the two sizes.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.