← 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 is the primary use case for `collections.ChainMap` compared to merging dicts with `{**d1, **d2}`?

    Answer: ChainMap creates a live view that reflects changes to the underlying dicts

    ChainMap holds references to the original dicts, so mutations to them are reflected in the ChainMap, unlike a merged copy.

  2. When using `defaultdict(int)`, what is the default value assigned to a newly accessed missing key?

    Answer: 0

    int() called with no arguments returns 0, so defaultdict(int) initializes missing keys to 0.

  3. Which method would you use to get all elements from a Counter, including repeats, as an iterator?

    Answer: counter.elements()

    `elements()` returns an iterator yielding each element repeated as many times as its count.

  4. What happens if you create a `namedtuple` field name that starts with an underscore?

    Answer: Raises a ValueError unless rename=True is passed

    Field names starting with underscore are invalid; passing rename=True auto-renames them to positional names like _0, _1.

  5. How do you add a new child scope to an existing `ChainMap` for temporary overrides?

    Answer: chainmap.new_child(new_dict)

    `new_child(m)` creates a new ChainMap with m as the first map, making it the highest-priority scope.

  6. What is the difference between `deque.rotate(1)` and `deque.rotate(-1)`?

    Answer: rotate(1) rotates right (last→first); rotate(-1) rotates left (first→last)

    Positive rotation moves elements from the right end to the left; negative rotation moves elements from the left end to the right.

  7. In a `Counter`, what does accessing a missing key return (without raising an exception)?

    Answer: 0

    Counter inherits from dict but overrides `__missing__` to return 0 for absent keys instead of raising KeyError.