C++ Coding Interview Questions With Solutions
Master the C++ coding interview questions that appear most often, with working solutions, patterns, complexity notes, and tips for staying calm under a timer.
The most common C++ coding interview questions with solutions fall into about ten patterns: hash maps, pointer manipulation, sorting plus greedy, sliding window, binary search, heaps, graph traversal, cache design, dynamic programming, and backtracking. Learn the pattern behind each problem, write it with the right STL container, and state its time and space complexity out loud. That combination matters more than memorizing any single answer.
TL;DR
- Interviewers reuse a small set of patterns; learning ten covers most C++ screens.
- Know your STL:
unordered_map,priority_queue,sort, andvectorappear in nearly every answer. - Always state time and space complexity after coding.
- Linked list and LRU problems test pointer and memory discipline, which is where C++ differs from other languages.
- Practice under a timer, not just untimed at home.
- Tools like CloakAI can help you review and understand solutions while you prepare.
Why Do Interviewers Ask C++ Questions?
C++ exposes how you think about memory, performance, and data layout. A candidate who picks vector over list, avoids needless copies, and passes by reference signals real fluency. A concrete habit to adopt: pass large containers as const vector<int>& whenever you don't mutate them.
What Are the Top C++ Interview Questions and Solutions?
Each problem below includes the pattern, a compact solution, and the complexity you should quote.
1. Two Sum (Hash Map)
Store each value's index; for each element, check whether target - x was already seen.
vector<int> twoSum(vector<int>& a, int target) {
unordered_map<int,int> idx;
for (int i = 0; i < (int)a.size(); i++) {
auto it = idx.find(target - a[i]);
if (it != idx.end()) return {it->second, i};
idx[a[i]] = i;
}
return {};
}
Complexity: O(n) time, O(n) space.
2. Reverse a Linked List (Pointers)
Walk the list once, flipping each next pointer.
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
while (head) {
ListNode* next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
Complexity: O(n) time, O(1) space.
3. Merge Intervals (Sort + Greedy)
Sort by start, then extend the last interval whenever the next one overlaps.
vector<vector<int>> merge(vector<vector<int>>& v) {
sort(v.begin(), v.end());
vector<vector<int>> out;
for (auto& cur : v) {
if (!out.empty() && cur[0] <= out.back()[1])
out.back()[1] = max(out.back()[1], cur[1]);
else out.push_back(cur);
}
return out;
}
Complexity: O(n log n) time, dominated by the sort.
4. Longest Substring Without Repeating Characters (Sliding Window)
Track the last index of each character and move the left edge past duplicates.
int lengthOfLongestSubstring(string s) {
vector<int> last(256, -1);
int left = 0, best = 0;
for (int r = 0; r < (int)s.size(); r++) {
unsigned char c = s[r];
if (last[c] >= left) left = last[c] + 1;
last[c] = r;
best = max(best, r - left + 1);
}
return best;
}
Complexity: O(n) time, O(1) space for a fixed 256-character alphabet.
5. Search in Rotated Sorted Array (Binary Search)
At each step, one half is always sorted. Decide which half contains the target.
int search(vector<int>& a, int t) {
int lo = 0, hi = (int)a.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == t) return mid;
if (a[lo] <= a[mid]) {
if (a[lo] <= t && t < a[mid]) hi = mid - 1;
else lo = mid + 1;
} else {
if (a[mid] < t && t <= a[hi]) lo = mid + 1;
else hi = mid - 1;
}
}
return -1;
}
Complexity: O(log n) time. Computing mid as lo + (hi - lo) / 2 avoids integer overflow, a detail interviewers like to hear.
6. Kth Largest Element (Min-Heap)
Keep a min-heap of size k; the top is the answer.
int findKthLargest(vector<int>& a, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
for (int x : a) {
pq.push(x);
if ((int)pq.size() > k) pq.pop();
}
return pq.top();
}
Complexity: O(n log k) time, O(k) space.
7. Number of Islands (DFS Flood Fill)
Scan the grid; each time you find a '1', sink the whole island and increment the count.
void dfs(vector<vector<char>>& g, int i, int j) {
if (i < 0 || j < 0 || i >= (int)g.size() || j >= (int)g[0].size() || g[i][j] != '1') return;
g[i][j] = '0';
dfs(g, i+1, j); dfs(g, i-1, j); dfs(g, i, j+1); dfs(g, i, j-1);
}
int numIslands(vector<vector<char>>& g) {
int count = 0;
for (int i = 0; i < (int)g.size(); i++)
for (int j = 0; j < (int)g[0].size(); j++)
if (g[i][j] == '1') { dfs(g, i, j); count++; }
return count;
}
Complexity: O(m·n) time. Mention that deep recursion can overflow the stack on huge grids, and offer BFS as the alternative.
8. LRU Cache (Hash Map + Doubly Linked List)
Use std::list plus an unordered_map of iterators, which avoids manual new and delete.
class LRUCache {
int cap;
list<pair<int,int>> items;
unordered_map<int, list<pair<int,int>>::iterator> pos;
public:
LRUCache(int c) : cap(c) {}
int get(int k) {
auto it = pos.find(k);
if (it == pos.end()) return -1;
items.splice(items.begin(), items, it->second);
return it->second->second;
}
void put(int k, int v) {
auto it = pos.find(k);
if (it != pos.end()) {
it->second->second = v;
items.splice(items.begin(), items, it->second);
return;
}
if ((int)items.size() == cap) {
pos.erase(items.back().first);
items.pop_back();
}
items.emplace_front(k, v);
pos[k] = items.begin();
}
};
Complexity: O(1) average for both get and put.
9. House Robber (Dynamic Programming)
At each house, choose the better of skipping it or robbing it plus the best from two houses back.
int rob(vector<int>& a) {
int two = 0, one = 0;
for (int x : a) {
int cur = max(one, two + x);
two = one;
one = cur;
}
return one;
}
Complexity: O(n) time, O(1) space. For more on this category, see our guide to dynamic programming interview questions and answers.
10. Generate Parentheses (Backtracking)
Add ( while fewer than n are open, and add ) only while closes are fewer than opens.
void go(int n, int open, int close, string& cur, vector<string>& res) {
if ((int)cur.size() == 2 * n) { res.push_back(cur); return; }
if (open < n) { cur.push_back('('); go(n, open+1, close, cur, res); cur.pop_back(); }
if (close < open) { cur.push_back(')'); go(n, open, close+1, cur, res); cur.pop_back(); }
}
Complexity: proportional to the nth Catalan number of valid outputs, roughly O(4^n / √n).
Which Pattern Goes With Which Problem?
| Pattern | Typical Problem | Key STL Tool |
|---|---|---|
| Hash map | Two Sum | unordered_map |
| Two pointers / pointers | Reverse List | raw pointers |
| Sort + greedy | Merge Intervals | sort |
| Sliding window | Longest Substring | vector, unordered_map |
| Binary search | Rotated Array | index math |
| Heap | Kth Largest | priority_queue |
| DFS/BFS | Number of Islands | recursion, queue |
| Design | LRU Cache | list, unordered_map |
| DP | House Robber | rolling variables |
| Backtracking | Parentheses | string, recursion |
How Should You Explain Your C++ Solution Out Loud?
Use a four-step script: restate the problem, name the pattern, code it while narrating, then give complexity and edge cases. Spend the final minute testing an empty input and a single-element input. Interviewers weigh communication heavily, and knowing how to explain Big O complexity in coding interviews is a quick win.
What Common C++ Mistakes Cost Candidates Offers?
- Forgetting to cast
size()(an unsigned type) before comparing with negative numbers. - Copying large vectors by value instead of by reference.
- Leaking memory with raw
newin design questions; prefer STL containers or smart pointers. - Overflowing
intwhen summing or computing midpoints. - Skipping the empty-input check.
How Can CloakAI Help You Practice and Perform?
Knowing patterns is different from recalling them under a timer. CloakAI is an invisible AI interview assistant that reads the problem on your screen and surfaces a step-by-step solution with explanation, so you can study how an answer is structured and stay on track. Read the Terms of Service and your assessment's rules before using any tool, and check how platforms behave in our breakdown of whether HackerRank can detect AI coding tools. You can learn more at cloakai.me.
FAQ
Q: What are the most common C++ coding interview questions? A: Two Sum, Reverse Linked List, Merge Intervals, Longest Substring Without Repeating Characters, Rotated Array Search, Kth Largest Element, Number of Islands, LRU Cache, House Robber, and Generate Parentheses appear repeatedly across companies.
Q: How many C++ problems should I practice before an interview? A: Aim for roughly 50 to 100 problems spread across the major patterns rather than 300 random ones. Depth on each pattern beats volume.
Q: Should I use STL in a C++ coding interview?
A: Yes, unless the interviewer says otherwise. Using vector, unordered_map, and priority_queue is expected and saves time for edge-case testing.
Q: Is recursion or iteration better for C++ interviews? A: Use whichever is clearer, but mention stack depth risk for recursion. Offer an iterative or BFS alternative for deep inputs.
Q: Can an AI assistant help with C++ interview prep? A: Yes. CloakAI can walk through solutions and explanations as you practice, helping you understand why an approach works rather than just what the code is.
Preparing for a live interview? See how CloakAI helps in real time →