โ† 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. Which collection type is best suited for implementing a thread-safe FIFO queue in Python?

    Answer: collections.deque

    deque's append() and popleft() operations are atomic in CPython, making it safe for use as a FIFO queue in single-producer single-consumer scenarios.

  2. What does `Counter & Counter` (intersection) compute?

    Answer: Minimum counts (keeps only shared elements with min count)

    Counter intersection keeps elements present in both counters, taking the minimum count for each.

  3. Which attribute of a `namedtuple` class holds default values for fields (Python 3.6.1+)?

    Answer: _field_defaults

    `_field_defaults` is a dict mapping field names to their default values defined at class creation.

  4. How does `collections.defaultdict` differ from `dict.setdefault()`?

    Answer: defaultdict inserts on read access; setdefault only inserts if explicitly called

    defaultdict automatically inserts the default value when a missing key is accessed; setdefault must be called explicitly and only inserts once per call.

  5. What is the output of: `from collections import deque; d = deque([1,2,3], maxlen=3); d.append(4); print(list(d))`?

    Answer: [2, 3, 4]

    With maxlen=3, appending a 4th element discards the oldest element (1) from the left, leaving [2, 3, 4].

  6. Which statement about `collections.OrderedDict.popitem()` is true in Python 3.7+?

    Answer: It accepts last=True/False to pop from either end

    OrderedDict.popitem(last=True) removes the last inserted item; passing last=False removes the first inserted item.

  7. What does `namedtuple._make(iterable)` do?

    Answer: Creates a named tuple instance from an iterable

    `_make()` is a classmethod that creates a new named tuple instance from any iterable, equivalent to unpacking.