Return true if every value in the slice is distinct (no value repeats), and
false otherwise. An empty slice is all unique.
allUnique(nums)
allUnique([]int{1, 2, 3}) // → true
allUnique([]int{1, 2, 2}) // → false
allUnique([]int{}) // → true
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.
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.
false immediately.true.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.
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.
"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.
def all_unique(nums):
seen = set()
for n in nums:
if n in seen:
return False
seen.add(n)
return True
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.