KatInterview

C++ Implementation Details: Containers and Polymorphism

Data Structure DesignModel answer
MediumModel answerData Structure Designc++data-structuresperformance

Last updated

Explain the internal mechanics of std::vector growth, std::unordered_map collision handling, and virtual function dispatch in C++.

Describe the following C++ implementation details:

  1. std::vector::push_back complexity and memory management:

    • What are the amortized and worst-case time complexities?
    • How does capacity expansion work (growth strategy, reallocation process)?
    • What happens to iterators and references during reallocation?
    • How do move semantics affect the reallocation process?
  2. std::unordered_map internal structure:

    • How are elements stored and organized internally?
    • How are hash collisions resolved?
    • What triggers a rehash, and what happens during one?
    • What are the complexity guarantees for common operations?
    • What gets invalidated when elements are inserted or removed?
  3. Virtual functions and runtime polymorphism:

    • What problem do virtual functions solve?
    • How is dynamic dispatch implemented at the machine level?
    • What are the runtime and memory overheads?
    • When must destructors be virtual, and why?
    • What are the trade-offs compared to compile-time alternatives?

Hints

Hint 1

For vector growth, think about why geometric expansion is necessary for amortized constant time.

Hint 2

Consider how unordered_map must preserve references even when the table is restructured.

Hint 3

Virtual dispatch requires runtime lookups—what data structure makes this possible?