Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

Which statement about using a hash set versus sorting to detect duplicates in an array of n integers is correct?

  1. A. Both take O(n) worst-case time
  2. B. Hashing takes expected O(n) time and O(n) space; sorting takes O(n log n) time and can use O(1) extra space (heap sort)
  3. C. Sorting uses more space than hashing
  4. D. Hashing guarantees O(n) worst-case time

Correct answer: B. Hashing takes expected O(n) time and O(n) space; sorting takes O(n log n) time and can use O(1) extra space (heap sort)

Hash operations are O(1) only on average; an adversarial input can cause collisions. Sorting then scanning adjacent pairs is deterministic O(n log n) and can be done in place.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic