252. How can sorting help check whether an array contains duplicates, and what are the alternatives?
EasySorting
Technical
Show model answer
The brute-force check compares every pair in O(n²) time and O(1) space. Sorting first (O(n log n), in place with heap sort) brings equal values next to each other, so one linear scan comparing `a[i]` with `a[i + 1]` answers the question.
A hash set gives O(n) expected time but O(n) extra space. Choose sorting when memory is tight or the array may be modified; choose hashing when speed matters and memory is available.