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?
- A. Hash lookups let each run start be detected in O(1), and only run starts (values whose predecessor is missing) are walked.
- B. A hash map sorts the values automatically.
- C. Consecutive integers are always adjacent in memory.
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- When tracking the first occurrence of every value for an order-preserving de-duplication, which structure gives expected O(1) membership…
- A subarray's average is at least K exactly when which quantity is non-negative for that subarray?
- Convert the infix expression a+b(c-d)/e to postfix with the shunting-yard algorithm (operators '+', '-', '', '/' with '' and '/' binding…
- A 3-litre jug and a 5-litre jug start empty and you can fill either, empty either, or pour one into the other until one is full or empty…
- Reverse the sublist between positions 3 and 6 (1-based, inclusive) of the list 1, 2, 3, 4, 5, 6, 7, 8. What value is at position 4 of the…
- Rotate the list 1, 2, 3, 4, 5, 6, 7 to the right by 10 positions (each rotation moves the last node to the front). What value is at the…