Interview Q&A · C++ · 10 questions in this topic
Common Coding Tasks — C++ Interview Q&A
Implement-it-now favorites — strings, two pointers, frequency maps and design mini-tasks with idiomatic solutions. Part of Tricky Outputs & Coding Tasks · 213 questions in the C++ bank.
How do you reverse a string in place?
Answer
Two pointers from both ends swapping inward is O(n) time, O(1) space. std::reverse expresses it directly; std::string is mutable, string_view is not (observe-only).
State the complexity and the mutation requirement before coding.
Example
#include <algorithm> #include <string> void reverse_in_place(std::string& s) { std::reverse(s.begin(), s.end()); // O(n), O(1) }
How do you check if two strings are anagrams?
Answer
Count frequencies (array of 26 for lowercase, unordered_map generally) and compare: O(n) time, O(1)/O(k) space. Sorting both is O(n log n) — correct but slower. Early-exit on length mismatch.
Ask about character set and case sensitivity before choosing the counter.
Example
#include <string> #include <array> bool anagram(std::string_view a, std::string_view b) { if (a.size() != b.size()) return false; std::array<int, 256> c{}; for (unsigned char ch : a) ++c[ch]; for (unsigned char ch : b) if (--c[ch] < 0) return false; return true; }
How do you find duplicates in an array efficiently?
Answer
Hash set tracking gives O(n) time, O(n) space with early exit on first repeat. Sorting first gives O(n log n) time, O(1) extra space. Floyd cycle detection applies when values are constrained to indices (classic n+1 numbers problem) for O(1) space.
Ask whether mutation and extra memory are allowed — the constraint picks the algorithm.
Example
#include <unordered_set> #include <vector> bool has_dup(const std::vector<int>& v) { std::unordered_set<int> seen; for (int x : v) if (!seen.insert(x).second) return true; return false; }
How do you implement two-sum (return indices)?
Answer
One pass with a hash map from value to index: for each x, look for complement = target - x among seen values; hit returns immediately, miss stores x. O(n) time, O(n) space, single pass.
Clarify duplicates, exactly-one-solution guarantees, and whether 1- or 0-based indices are expected.
Example
#include <unordered_map> #include <vector> std::pair<int,int> two_sum(const std::vector<int>& a, int target) { std::unordered_map<int,int> at; for (int i = 0; i < (int)a.size(); ++i) { auto it = at.find(target - a[i]); if (it != at.end()) return {it->second, i}; at[a[i]] = i; } return {-1, -1}; }
How do you design an LRU cache (sketch the C++ approach)?
Answer
Hash map (key to list iterator) plus a doubly-linked list in recency order: get/put splice the node to front in O(1); eviction pops the back. std::list gives splice without invalidation; unordered_map gives O(1) lookup.
Mention mutex wrapping for thread safety and capacity-zero edge cases.
Key points
- 1Map — key to list position, O(1) lookup.
- 2List — recency order, O(1) splice/evict.
- 3Ops — touch moves to front; insert evicts back at capacity.
Example
// sketch: // std::list<std::pair<int,int>> order; // front = recent // std::unordered_map<int, ListIt> pos; // key -> position
💡 Map-plus-list with O(1) everything is the answer skeleton; splice is the key operation.
How do you remove duplicates from a sorted vector in place?
Answer
std::unique compacts unique elements forward (returning the new logical end) and erase truncates — the sorted specialization of erase-remove. O(n) time, O(1) space. For unsorted input, sort first (O(n log n)) or hash-filter (O(n) space).
unique only removes adjacent duplicates, which is why sortedness is a precondition.
Example
std::vector<int> v{1, 1, 2, 3, 3}; v.erase(std::unique(v.begin(), v.end()), v.end()); // {1,2,3}
How do you find the kth largest element efficiently?
Answer
nth_element partially orders so position k holds its final value with all larger before it: average O(n), no full sort. A size-k min-heap streams answers in O(n log k). Full sort is O(n log n) — simplest but slowest.
nth_element mutates order; copy first if the original sequence must survive.
Example
#include <algorithm> int kth_largest(std::vector<int> v, int k) { // 1-based std::nth_element(v.begin(), v.begin() + (k - 1), v.end(), std::greater<int>{}); return v[k - 1]; }
How do you detect a cycle in a linked list?
Answer
Floyd tortoise-and-hare: slow advances one step, fast two; meeting means a cycle, fast hitting null means none. O(n) time, O(1) space. A visited hash set also works in O(n) space.
To find the cycle start, reset one pointer to head after meeting and advance both at equal speed.
Example
struct Node { int v; Node* next = nullptr; }; bool has_cycle(Node* h) { Node *slow = h, *fast = h; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; }
How do you implement a thread-safe singleton in modern C++?
Answer
Function-local static (Meyers singleton): thread-safe initialization since C++11, deterministic destruction, lazy. Delete copy/move. For eager or ordered lifetimes, consider a Schwartz-counter or an explicit init function instead.
Double-checked locking by hand is obsolete — the language guarantees the local static.
Example
class Config { public: static Config& instance() { static Config one; // thread-safe init (C++11) return one; } Config(const Config&) = delete; Config& operator=(const Config&) = delete; private: Config() = default; };
💡 Meyers singleton plus deleted copies is the complete modern answer.
How do you write a small RAII wrapper (e.g. for a C handle)?
Answer
Own the handle in a move-only class: constructor acquires (throwing on failure), destructor releases noexcept, move transfers and nulls the source, copy deleted. Or alias unique_ptr with a custom deleter for the zero-boilerplate version.
The wrapper converts every manual close/free into automatic, exception-safe cleanup.
Example
#include <cstdio> struct File { explicit File(const char* p) : f_(std::fopen(p, "r")) { if (!f_) throw std::runtime_error("open failed"); } ~File() noexcept { if (f_) std::fclose(f_); } File(File&& o) noexcept : f_(o.f_) { o.f_ = nullptr; } File(const File&) = delete; private: std::FILE* f_ = nullptr; };
Recommended resourcesAffiliate links · may earn us a commission