Chapter 20 Advanced 61 Questions

Practice Questions — STL Containers - vector, list, map, set, stack, queue

← Back to Notes
11 Easy
15 Medium
11 Hard

Topic-Specific Questions

Question 1
Easy
What is the output?
vector<int> v = {10, 20, 30};
v.push_back(40);
cout << v.size() << " " << v[3];
push_back adds to the end. Size increases by 1.
4 40
Question 2
Easy
What is the output?
set<int> s = {5, 2, 8, 2, 1, 5};
cout << s.size();
set stores unique elements only.
4
Question 3
Easy
What is the output?
set<int> s = {30, 10, 20};
for (int x : s) cout << x << " ";
set maintains sorted order.
10 20 30
Question 4
Easy
What is the output?
stack<int> st;
st.push(10);
st.push(20);
st.push(30);
cout << st.top();
st.pop();
cout << " " << st.top();
Stack is LIFO. top() shows the last pushed element.
30 20
Question 5
Easy
What is the output?
queue<int> q;
q.push(10);
q.push(20);
q.push(30);
cout << q.front() << " " << q.back();
Queue is FIFO. front() is the first element pushed.
10 30
Question 6
Easy
What is the output?
map<string, int> m;
m["Kiran"] = 78;
m["Arjun"] = 85;
for (auto& [k, v] : m) cout << k << " ";
map iterates in sorted order of keys.
Arjun Kiran
Question 7
Medium
What is the output?
vector<int> v;
v.reserve(10);
v.push_back(1);
v.push_back(2);
cout << v.size() << " " << v.capacity();
reserve() sets capacity but does not change size.
2 10
Question 8
Medium
What is the output?
priority_queue<int> pq;
pq.push(10);
pq.push(50);
pq.push(30);
pq.push(20);
cout << pq.top();
pq.pop();
cout << " " << pq.top();
priority_queue is a max-heap by default.
50 30
Question 9
Medium
What is the output?
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(30);
pq.push(10);
pq.push(50);
cout << pq.top();
greater creates a min-heap.
10
Question 10
Medium
What is the output?
multiset<int> ms = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
cout << ms.count(5) << " " << ms.count(7);
multiset allows duplicates. count() returns the number of occurrences.
3 0
Question 11
Medium
What is the output?
map<string, int> m;
m["Priya"] = 92;
m["Arjun"] = 85;
cout << m.size() << endl;
m["Ravi"];  // Access non-existent key
cout << m.size() << " " << m["Ravi"];
The [] operator on map creates a default entry if the key does not exist.
2
3 0
Question 12
Medium
What is the output?
set<int> s = {1, 3, 5, 7, 9};
auto lb = s.lower_bound(4);
auto ub = s.upper_bound(7);
cout << *lb << " " << *ub;
lower_bound returns first element >= value. upper_bound returns first element > value.
5 9
Question 13
Hard
What is the output?
map<int, string> m = {{3, "C"}, {1, "A"}, {2, "B"}};
auto it = m.begin();
cout << it->first << ":" << it->second << " ";
++it; ++it;
cout << it->first << ":" << it->second;
map iterates in sorted order of keys.
1:A 3:C
Question 14
Hard
What is the output?
vector<int> v;
cout << v.size() << " ";
v.resize(5, 42);
cout << v.size() << " " << v[0] << " " << v[4] << " ";
v.resize(3);
cout << v.size() << " " << v[2];
resize(n, val) changes size. If growing, new elements get val. If shrinking, excess elements are removed.
0 5 42 42 3 42
Question 15
Hard
What is the output?
deque<int> dq = {20, 30, 40};
dq.push_front(10);
dq.push_back(50);
dq.pop_front();
dq.pop_back();
cout << dq.front() << " " << dq.back() << " " << dq[1];
push_front/push_back add to ends, pop_front/pop_back remove from ends.
20 40 30
Question 16
Medium
What is the output?
set<int> s = {5, 10, 15, 20, 25};
auto it = s.find(15);
if (it != s.end()) s.erase(it);
for (int x : s) cout << x << " ";
find returns an iterator. erase(iterator) removes that element.
5 10 20 25
Question 17
Hard
What is the output?
map<int, string> m = {{1,"one"}, {2,"two"}, {3,"three"}};
for (auto it = m.begin(); it != m.end(); ) {
    if (it->first % 2 == 0)
        it = m.erase(it);
    else
        ++it;
}
for (auto& [k, v] : m) cout << k << ":" << v << " ";
erase returns iterator to next element. Only erase even keys.
1:one 3:three
Question 18
Medium
What is the output?
vector<int> v = {1, 2, 3};
v.insert(v.end(), {4, 5, 6});
cout << v.size() << " " << v.back();
insert with initializer_list appends multiple elements.
6 6
Question 19
Hard
What is the output?
priority_queue<pair<int,string>, vector<pair<int,string>>, greater<pair<int,string>>> pq;
pq.push({3, "Kiran"});
pq.push({1, "Arjun"});
pq.push({2, "Priya"});
cout << pq.top().second;
Min-heap with pairs. Pairs compare lexicographically (first element first).
Arjun
Question 20
Easy
What is the output?
vector<int> v;
cout << v.empty() << " ";
v.push_back(10);
cout << v.empty() << " " << v.front();
empty() returns true (1) if the vector has no elements.
1 0 10

Mixed & Application Questions

Question 1
Easy
What is the output?
vector<int> v = {1, 2, 3, 4, 5};
v.pop_back();
v.pop_back();
cout << v.size() << " " << v.back();
pop_back removes the last element.
3 3
Question 2
Easy
What is the output?
set<int> s = {10, 20, 30};
s.insert(20);
s.insert(40);
cout << s.size();
Inserting a duplicate into a set has no effect.
4
Question 3
Easy
What is the output?
stack<char> st;
st.push('A');
st.push('B');
st.push('C');
st.pop();
cout << st.top() << " " << st.size();
Stack is LIFO. pop() removes the top element.
B 2
Question 4
Medium
What is the output?
map<char, int> freq;
string s = "banana";
for (char c : s) freq[c]++;
cout << freq['a'] << " " << freq['n'] << " " << freq.size();
freq[c]++ increments the count for each character.
3 2 3
Question 5
Medium
What is the output?
set<int> s = {1, 2, 3, 4, 5};
s.erase(3);
cout << s.count(3) << " " << s.size();
erase removes the element. count checks if it exists.
0 4
Question 6
Medium
What is the output?
vector<int> v = {10, 20, 30};
v.insert(v.begin() + 1, 15);
for (int x : v) cout << x << " ";
insert(pos, val) inserts val before the given position.
10 15 20 30
Question 7
Medium
What is the output?
unordered_map<string, int> m;
m["Arjun"] = 85;
m["Priya"] = 92;
cout << (m.find("Arjun") != m.end()) << " ";
cout << (m.find("Kiran") != m.end());
find() returns end() if the key is not found.
1 0
Question 8
Hard
What is the output?
priority_queue<int> pq;
for (int x : {4, 1, 7, 3, 8, 2}) pq.push(x);
int sum = 0;
while (pq.size() > 3) {
    sum += pq.top();
    pq.pop();
}
cout << sum << " " << pq.top();
Max-heap pops the largest elements first. Stop when 3 elements remain.
19 3
Question 9
Hard
What is the output?
multimap<string, int> mm;
mm.insert({"Arjun", 85});
mm.insert({"Arjun", 90});
mm.insert({"Arjun", 78});
mm.insert({"Priya", 92});
cout << mm.count("Arjun") << " " << mm.size();
multimap allows duplicate keys.
3 4
Question 10
Hard
What is the output?
set<int> s = {10, 20, 30, 40, 50};
auto it1 = s.lower_bound(25);
auto it2 = s.upper_bound(30);
auto it3 = s.lower_bound(60);
cout << *it1 << " " << *it2 << " " << (it3 == s.end());
lower_bound(25) returns first >= 25. upper_bound(30) returns first > 30. lower_bound(60) returns end() if no element >= 60.
30 40 1
Question 11
Hard
What is the output?
map<int, int> m = {{1, 10}, {2, 20}, {3, 30}};
m[2] = 25;
m.erase(1);
m.insert({4, 40});
for (auto& [k, v] : m) cout << k << ":" << v << " ";
[] overwrites existing values. erase removes by key. insert adds new entries.
2:25 3:30 4:40
Question 12
Medium
When would you choose unordered_map over map?
Think about time complexity and ordering requirements.
unordered_map provides O(1) average-case for insert, find, and erase, compared to O(log n) for map. Choose unordered_map when you do not need sorted order and want faster operations. Choose map when you need sorted iteration, lower_bound/upper_bound, or when the key type does not have a hash function.
Question 13
Hard
Why does the erase-iterate pattern require special care with maps and sets? Show the correct pattern.
Think about iterator invalidation.
When you erase an element from a map/set using an iterator, that iterator is invalidated. If you increment it after erasing, the behavior is undefined. The correct pattern is: it = m.erase(it) which returns an iterator to the next valid element. Alternatively, use m.erase(it++) which copies the iterator, increments the original, then erases the copy.
Question 14
Medium
What is the output?
unordered_map<string, int> m;
m["a"] = 1;
m["b"] = 2;
m["c"] = 3;
cout << m.size() << " " << m.count("b") << " " << m.count("d");
count returns 1 if key exists, 0 if not.
3 1 0
Question 15
Hard
What is the output?
set<int> a = {1, 2, 3, 4, 5};
set<int> b = {3, 4, 5, 6, 7};
vector<int> result;
set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(result));
for (int x : result) cout << x << " ";
set_intersection finds common elements between two sorted ranges.
3 4 5
Question 16
Easy
What is the output?
stack<int> st;
st.push(1);
st.push(2);
st.push(3);
cout << st.size() << " ";
while (!st.empty()) {
    cout << st.top() << " ";
    st.pop();
}
Stack is LIFO. Elements come out in reverse order.
3 3 2 1
Question 17
Medium
What is the output?
queue<string> q;
q.push("Arjun");
q.push("Priya");
q.push("Kiran");
q.pop();
cout << q.front() << " " << q.size();
Queue is FIFO. pop removes the front element.
Priya 2

Multiple Choice Questions

MCQ 1
Which STL container stores elements in sorted order with no duplicates?
  • A. vector
  • B. set
  • C. unordered_set
  • D. list
Answer: B
B is correct. set stores unique elements in sorted order using a balanced BST. unordered_set is unsorted, vector and list maintain insertion order.
MCQ 2
What is the time complexity of push_back on a vector (amortized)?
  • A. O(1)
  • B. O(log n)
  • C. O(n)
  • D. O(n log n)
Answer: A
A is correct. push_back is amortized O(1). Occasionally it triggers a reallocation (O(n)), but averaged over many operations, it is O(1).
MCQ 3
Which container follows the Last-In-First-Out (LIFO) principle?
  • A. queue
  • B. deque
  • C. stack
  • D. priority_queue
Answer: C
C is correct. stack is LIFO -- the last element pushed is the first to be popped. queue is FIFO.
MCQ 4
What does v.at(i) do differently from v[i] for a vector?
  • A. No difference
  • B. at(i) throws out_of_range if i is out of bounds
  • C. at(i) is faster
  • D. at(i) returns a reference while [] returns a copy
Answer: B
B is correct. at(i) performs bounds checking and throws std::out_of_range if the index is invalid. [] has no bounds checking and causes undefined behavior on invalid access.
MCQ 5
What is the default behavior of priority_queue in C++?
  • A. Min-heap (smallest element at top)
  • B. Max-heap (largest element at top)
  • C. FIFO queue
  • D. Sorted array
Answer: B
B is correct. priority_queue is a max-heap by default. The largest element is always at the top. Use greater<T> to create a min-heap.
MCQ 6
What is the time complexity of find() on a set?
  • A. O(1)
  • B. O(log n)
  • C. O(n)
  • D. O(n log n)
Answer: B
B is correct. set uses a balanced BST internally, so find() is O(log n). For O(1) average lookup, use unordered_set.
MCQ 7
What happens when you use map[key] and the key does not exist?
  • A. Returns -1
  • B. Throws an exception
  • C. Inserts a new entry with a default-constructed value
  • D. Returns end() iterator
Answer: C
C is correct. The [] operator on a map inserts a default-constructed value (0 for int, empty string for string) if the key does not exist. This is a common source of bugs.
MCQ 8
Which container provides O(1) push/pop at both ends AND random access?
  • A. vector
  • B. list
  • C. deque
  • D. stack
Answer: C
C is correct. deque supports O(1) push_front/push_back, pop_front/pop_back, AND random access via []. vector does not have efficient push_front. list does not have random access.
MCQ 9
What is the difference between set and multiset?
  • A. set is sorted, multiset is unsorted
  • B. multiset allows duplicate elements, set does not
  • C. multiset uses a hash table, set uses a BST
  • D. set allows duplicates, multiset does not
Answer: B
B is correct. Both set and multiset are sorted and use balanced BSTs. The only difference is that multiset allows duplicate elements.
MCQ 10
How do you create a min-heap using priority_queue?
  • A. priority_queue<int, min>
  • B. priority_queue<int, vector<int>, greater<int>>
  • C. priority_queue<int, vector<int>, less<int>>
  • D. min_priority_queue<int>
Answer: B
B is correct. The full template is priority_queue<type, container, comparator>. Using greater<int> reverses the comparison, making the smallest element the top.
MCQ 11
What is the worst-case time complexity of find() on unordered_map?
  • A. O(1)
  • B. O(log n)
  • C. O(n)
  • D. O(n log n)
Answer: C
C is correct. unordered_map has O(1) average-case but O(n) worst-case due to hash collisions. If all keys hash to the same bucket, every operation degrades to linear time.
MCQ 12
Why can you NOT use pair as a key in unordered_map without a custom hash?
  • A. pair does not support comparison
  • B. pair does not have a default std::hash specialization
  • C. unordered_map does not support composite keys
  • D. pair is not a standard type
Answer: B
B is correct. unordered_map requires std::hash<Key> to be defined. There is no standard hash for std::pair. You must provide a custom hash functor or use map which only requires operator<.
MCQ 13
What does vector::reserve(100) do?
  • A. Sets the size to 100 and fills with zeros
  • B. Allocates memory for at least 100 elements without changing size
  • C. Limits the vector to a maximum of 100 elements
  • D. Creates 100 copies of the vector
Answer: B
B is correct. reserve() only allocates memory (sets capacity) without changing the size or adding elements. Use resize() to actually change the size.
MCQ 14
What internal data structure does std::set use?
  • A. Hash table
  • B. Sorted array
  • C. Red-black tree (balanced BST)
  • D. B-tree
Answer: C
C is correct. All major implementations (GCC libstdc++, Clang libc++, MSVC) use a red-black tree for set, map, multiset, and multimap. This guarantees O(log n) operations.
MCQ 15
Which container adaptor should you use for BFS (Breadth-First Search)?
  • A. stack
  • B. queue
  • C. priority_queue
  • D. deque
Answer: B
B is correct. BFS requires FIFO processing: explore nodes in the order they are discovered. queue provides exactly this behavior. stack would give DFS. priority_queue is used for Dijkstra's algorithm.
MCQ 16
What does v.clear() do on a vector?
  • A. Deletes the vector object
  • B. Removes all elements, size becomes 0, capacity may remain
  • C. Sets all elements to zero
  • D. Frees all allocated memory
Answer: B
B is correct. clear() removes all elements and sets size to 0, but the allocated memory (capacity) is typically not freed. To free memory, use the swap trick: vector<int>().swap(v).
MCQ 17
What is the time complexity of push and pop on a priority_queue?
  • A. O(1) for both
  • B. O(log n) for push, O(1) for pop
  • C. O(log n) for both push and pop
  • D. O(n) for push, O(log n) for pop
Answer: C
C is correct. priority_queue uses a binary heap. Both push (sift-up) and pop (sift-down) require O(log n) time. top() is O(1).
MCQ 18
Which container should you use for frequency counting when you need sorted output?
  • A. unordered_map
  • B. map
  • C. vector
  • D. set
Answer: B
B is correct. map stores key-value pairs sorted by key. When you iterate over a frequency map, keys appear in sorted order. unordered_map gives faster counting but unsorted iteration.

Coding Challenges

Challenge 1: Frequency Count and Print in Sorted Order

Easy
Given a string, count the frequency of each character and print the characters in sorted order along with their counts.
Sample Input
"programming"
Sample Output
a:1 g:2 i:1 m:2 n:1 o:1 p:1 r:2
Use a map<char, int> for automatic sorted order.
#include <iostream>
#include <map>
using namespace std;

int main() {
    string s = "programming";
    map<char, int> freq;
    for (char c : s) freq[c]++;
    for (auto& [ch, cnt] : freq)
        cout << ch << ":" << cnt << " ";
    cout << endl;
    return 0;
}

Challenge 2: Check If Parentheses Are Balanced Using Stack

Easy
Given a string containing parentheses '(', ')', '{', '}', '[', ']', determine if the input string is valid. An input string is valid if open brackets are closed by the same type and in the correct order.
Sample Input
"{[()]}"
Sample Output
Valid
Use a stack. Time complexity O(n).
#include <iostream>
#include <stack>
using namespace std;

int main() {
    string s = "{[()]}";
    stack<char> st;
    bool valid = true;
    for (char c : s) {
        if (c == '(' || c == '{' || c == '[')
            st.push(c);
        else {
            if (st.empty()) { valid = false; break; }
            char top = st.top(); st.pop();
            if ((c == ')' && top != '(') ||
                (c == '}' && top != '{') ||
                (c == ']' && top != '['))
                { valid = false; break; }
        }
    }
    if (!st.empty()) valid = false;
    cout << (valid ? "Valid" : "Invalid") << endl;
    return 0;
}

Challenge 3: Two Sum Using Unordered Map

Medium
Given a vector of integers and a target, find two indices such that the numbers at those indices add up to the target. Assume exactly one solution exists.
Sample Input
nums = {2, 7, 11, 15}, target = 9
Sample Output
Indices: 0 1
Use unordered_map for O(n) time complexity.
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int main() {
    vector<int> nums = {2, 7, 11, 15};
    int target = 9;
    unordered_map<int, int> seen;
    for (int i = 0; i < (int)nums.size(); i++) {
        int complement = target - nums[i];
        if (seen.count(complement)) {
            cout << "Indices: " << seen[complement] << " " << i << endl;
            break;
        }
        seen[nums[i]] = i;
    }
    return 0;
}

Challenge 4: Merge K Sorted Arrays Using Priority Queue

Hard
Given K sorted arrays, merge them into one sorted array. Use a min-heap (priority_queue with greater<>) to always extract the smallest current element.
Sample Input
arrays = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}
Sample Output
1 2 3 4 5 6 7 8 9
Use priority_queue<tuple<int,int,int>, vector<...>, greater<...>> storing {value, array_index, element_index}. Time: O(N log K).
#include <iostream>
#include <vector>
#include <queue>
#include <tuple>
using namespace std;

int main() {
    vector<vector<int>> arrays = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
    using T = tuple<int, int, int>;  // {value, array_idx, elem_idx}
    priority_queue<T, vector<T>, greater<T>> pq;

    for (int i = 0; i < (int)arrays.size(); i++)
        pq.push({arrays[i][0], i, 0});

    while (!pq.empty()) {
        auto [val, ai, ei] = pq.top();
        pq.pop();
        cout << val << " ";
        if (ei + 1 < (int)arrays[ai].size())
            pq.push({arrays[ai][ei + 1], ai, ei + 1});
    }
    cout << endl;
    return 0;
}

Challenge 5: Find First Non-Repeating Character Using Map and Queue

Medium
Given a stream of characters, find the first non-repeating character at each step. If all characters repeat, print -1.
Sample Input
"aabcbcd"
Sample Output
a -1 b b b b d
Use a queue to track order and an unordered_map for frequency. Process character by character.
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;

int main() {
    string stream = "aabcbcd";
    queue<char> q;
    unordered_map<char, int> freq;
    for (char c : stream) {
        freq[c]++;
        q.push(c);
        while (!q.empty() && freq[q.front()] > 1)
            q.pop();
        if (q.empty())
            cout << "-1 ";
        else
            cout << q.front() << " ";
    }
    cout << endl;
    return 0;
}

Challenge 6: Find K Closest Points to Origin Using Max-Heap

Hard
Given n points in 2D space, find the K closest points to the origin (0, 0). Use a max-heap of size K to maintain the K closest points seen so far.
Sample Input
points = {{3,3}, {5,-1}, {-2,4}, {1,1}, {-3,-2}}, K = 3
Sample Output
Closest 3 points: (1,1) (-3,-2) (-2,4)
Use priority_queue with custom comparator. Time: O(n log K).
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main() {
    vector<pair<int,int>> points = {{3,3}, {5,-1}, {-2,4}, {1,1}, {-3,-2}};
    int K = 3;

    // Max-heap: pop the farthest among the K closest
    auto dist = [](const pair<int,int>& p) {
        return p.first * p.first + p.second * p.second;
    };
    auto cmp = [&](const pair<int,int>& a, const pair<int,int>& b) {
        return dist(a) < dist(b);  // max-heap by distance
    };
    priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)> pq(cmp);

    for (auto& p : points) {
        pq.push(p);
        if ((int)pq.size() > K) pq.pop();
    }

    cout << "Closest " << K << " points: ";
    while (!pq.empty()) {
        auto [x, y] = pq.top(); pq.pop();
        cout << "(" << x << "," << y << ") ";
    }
    cout << endl;
    return 0;
}

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to learn C++ with a live mentor?

Explore our C++ Masterclass