โ† All HACKERRANK Flashcard Decks

Collections and Data Structures Flashcards

7 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning โ€” missed cards come back until you master them.

Read the first 7 Collections and Data Structures flashcards as text
  1. What does `collections.OrderedDict` guarantee that a regular `dict` does NOT guarantee in Python versions before 3.7?

    Answer: Insertion order preservation

    OrderedDict preserves the insertion order of keys, which regular dicts did not guarantee before Python 3.7.

  2. Which method of `collections.deque` removes and returns an element from the LEFT end?

    Answer: popleft()

    `popleft()` removes and returns the leftmost element of a deque in O(1) time.

  3. What is the output of: `from collections import Counter; c = Counter('aabbc'); print(c.most_common(2))`?

    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.

  4. What happens when you access a missing key in a `collections.defaultdict(list)`?

    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.

  5. Which named tuple method returns a new instance replacing specified fields with new values?

    Answer: _replace()

    `_replace()` returns a new named tuple instance with specified fields replaced by new values.

  6. What is the time complexity of `collections.deque.appendleft()`?

    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).

  7. How do you create a named tuple class called `Point` with fields `x` and `y`?

    Answer: Point = namedtuple('Point', ['x', 'y'])

    `collections.namedtuple('Point', ['x', 'y'])` creates a new tuple subclass with named fields.