Skip to interview prep
Apexed

How can sorting help check whether an array contains duplicates, and what are the alternatives?

EasySorting

Technical

Content review

Report an error

Not yet reviewed

Type or dictate your answer. Your draft is saved on this device.

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.

How can sorting help check whether an array contains duplicates, and what are the alternatives — Data structures & algorithms interview question — Apexed