Skip to the page

Templates and the STL · core

vector, deque, stack, queue and priority_queue

vector is the default container in coding tests. stack, queue and priority_queue are adaptors built on a vector or a deque. Know the cost of each operation and the calls that are unsafe on an empty container.

The notes

What you must know

  • vector stores its elements next to each other. v[i] is O(1); push_back and pop_back at the end are amortised O(1); insert or erase in the middle is O(n), because the later elements move.
  • When size() reaches capacity(), push_back allocates a bigger block and moves the elements there; then all iterators, pointers and references to elements are invalid. reserve(n) avoids repeated reallocation.
  • vector<int> a(n); makes n zeros; vector<vector<int>> g(n, vector<int>(m, 0)); makes an n by m grid. v[i] does not check the index; v.at(i) throws std::out_of_range.
  • deque adds and removes at both ends in O(1) and still allows d[i], but its elements are not in one block.
  • stack (last in, first out) and queue (first in, first out) wrap a deque by default. pop() returns nothing: read top() or front() first, then call pop().
  • Check empty() before top(), front() or pop(): on an empty container they are undefined behaviour.
  • priority_queue wraps a vector and keeps the largest element on top by default. top() is O(1); push() and pop() are O(log n).
  • For a min-heap write priority_queue<int, vector<int>, greater<int>> pq;. Use it for the k smallest items, merging sorted lists and Dijkstra.

The red pen

Common traps: mistake → fix

  • Mistake: pop() returns the removed element

    Fix: it returns void; call top() first.

  • Mistake: priority_queue gives the smallest first

    Fix: by default it gives the largest; use greater<int> for the smallest.

  • Mistake: push_back is always O(1)

    Fix: it is amortised O(1); a reallocation moves every element.

  • Mistake: An iterator stays valid after push_back

    Fix: a reallocation makes it invalid.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between size and capacity in a vector? What does reserve do?
  2. What is the time complexity of push_back? Why is it called amortised?
  3. How do you make a min-heap with priority_queue?
  4. What is the difference between stack, queue and deque?
  5. You keep an iterator into a vector and then call push_back. What can go wrong?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview