Data Structures & AlgorithmsVery hard

Why is a hash map (not a sorted array) used to find the longest run of consecutive integers in an unsorted array in linear expected time?

  1. A. Hash lookups let each run start be detected in O(1), and only run starts (values whose predecessor is missing) are walked.
  2. B. A hash map sorts the values automatically.
  3. C. Consecutive integers are always adjacent in memory.
  4. D. A hash map stores each value exactly once, so counting is trivial.

Correct answer: A. Hash lookups let each run start be detected in O(1), and only run starts (values whose predecessor is missing) are walked.

Walking only from values whose predecessor is absent means every value is visited a constant number of times in total. The O(1) lookup is what makes the membership test cheap.

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

Exams that ask this topic