Hackerrank Collections and Data Structures 2 — Questions and Answers
Question 1: What does `collections.OrderedDict` guarantee that a regular `dict` does NOT guarantee in Python versions before 3.7?
- Key uniqueness
- Insertion order preservation (Correct answer)
- O(1) lookup time
- Thread safety
Correct answer: Insertion order preservation
OrderedDict preserves the insertion order of keys, which regular dicts did not guarantee before Python 3.7.
Question 2: Which method of `collections.deque` removes and returns an element from the LEFT end?
- pop()
- popleft() (Correct answer)
- remove()
- shift()
Correct answer: popleft()
`popleft()` removes and returns the leftmost element of a deque in O(1) time.
Question 3: What is the output of: `from collections import Counter; c = Counter('aabbc'); print(c.most_common(2))`?
- [('a', 2), ('b', 2)] (Correct answer)
- [('a', 2), ('b', 2), ('c', 1)]
- {'a': 2, 'b': 2}
- [('c', 1), ('b', 2)]
Correct answer: [('a', 2), ('b', 2)]
`most_common(2)` returns the two most frequent elements as a list of (element, count) tuples; ties are ordered arbitrarily.
Question 4: What happens when you access a missing key in a `collections.defaultdict(list)`?
- Raises KeyError
- Returns None
- Creates an entry with an empty list (Correct answer)
- Creates an entry with value 0
Correct answer: Creates an entry with an empty list
defaultdict calls its factory function (list) to create a default value for missing keys, inserting an empty list.
Question 5: Which named tuple method returns a new instance replacing specified fields with new values?
- _replace() (Correct answer)
- _update()
- _modify()
- _set()
Correct answer: _replace()
`_replace()` returns a new named tuple instance with specified fields replaced by new values.
Question 6: What is the time complexity of `collections.deque.appendleft()`?
- O(n)
- O(log n)
- O(1) (Correct answer)
- O(n log n)
Correct answer: O(1)
deque is implemented as a doubly-linked list, so appendleft() is O(1) unlike list.insert(0, x) which is O(n).
Question 7: How do you create a named tuple class called `Point` with fields `x` and `y`?
- Point = namedtuple('Point', ['x', 'y']) (Correct answer)
- Point = namedtuple(['x', 'y'])
- Point = NamedTuple('Point', x, y)
- Point = tuple.named('Point', 'x y')
Correct answer: Point = namedtuple('Point', ['x', 'y'])
`collections.namedtuple('Point', ['x', 'y'])` creates a new tuple subclass with named fields.
What does `collections.OrderedDict` guarantee that a regular `dict` does NOT guarantee in Python versions before 3.7?