Why it works
- All we need to know about a number is whether we have met it before. A set stores exactly that and answers at once, without walking back over the array.
- The first number already in the set is a repeat: the answer is true, and the rest of the array does not matter.
- If the array ends with no hit, every number went into the set as new, so all of them differ: false.
Complexity
Time O(n): one pass, a set lookup is O(1) on average. Sorting and comparing neighbours would take O(n log n). Memory O(n): the set may hold every number.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗