All Unique

All Unique

Return true if every value in the slice is distinct (no value repeats), and false otherwise. An empty slice is all unique.

allUnique(nums)

Examples

allUnique([]int{1, 2, 3})     // → true
allUnique([]int{1, 2, 2})     // → false
allUnique([]int{})            // → true

Walkthrough

Thinking it through

The question is whether any value shows up more than once. The direct way to check "has this value appeared before?" is to keep a running record of everything you've seen, and check it before adding each new value.

Why comparing every pair is wasteful

Checking every pair of positions for a match costs time proportional to the square of the list's length. But by the time you've reached any position in a single left-to-right scan, you already know every value before it — no need to rescan backward, just remember it and check quickly.

Building the approach

  1. Keep a set: "values seen so far," starting empty.
  2. Walk the list. For each value, check whether it's already in the set.
  3. If it is, you've found a repeat — stop and report false immediately.
  4. If not, add it, and move to the next value.
  5. If you reach the end without a match, no value ever repeated — return true.

Why checking before adding is essential

Check membership before inserting the current value, not after. If you inserted first, every value would trivially "find itself" in the set and falsely register as a duplicate.

Why this is efficient

Each value is looked up and inserted at most once, both at constant time on average — so the whole scan costs time proportional to the list length, a big improvement over the squared cost of pairwise comparison. The early exit is a nice bonus: with an early repeat, you don't even need to look at the rest of the list.

Why this generalizes

"Have I seen this before?" comes up constantly — detecting duplicates, finding the first repeat, checking for cycles. All lean on the same idea: keep a running set of what's been observed, and use it for constant-time lookups instead of rescanning.

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