C++ course menu
C++ Coding Challenges for Interviews (With Solutions)
Classic C++ coding interview problems with hints and full solutions: two sum, valid parentheses, reverse words, anagram check, maximum subarray (Kadane), merge sorted arrays, binary search, first unique character, rotate an array, longest substring without repeating characters, and reverse a linked list.
On this page
- Challenge 1: Two Sum
- Challenge 2: Valid Parentheses
- Challenge 3: Reverse the Words in a Sentence
- Challenge 4: Valid Anagram
- Challenge 5: Maximum Subarray Sum
- Challenge 6: Merge Two Sorted Arrays
- Challenge 7: Binary Search
- Challenge 8: Rotate an Array
- Challenge 9: Longest Substring Without Repeating Characters
- Challenge 10: Reverse a Linked List
- How to approach a coding interview
These are classic problems from coding interviews and online assessments. Each one teaches a reusable technique, such as hashing, stacks, two pointers, sliding windows or running totals. Try each for at least 10 minutes before opening the hint, and state the time and space complexity of your answer, because interviewers always ask.
Challenge 1: Two Sum#
Two Sum
Return the indexes of two numbers in a vector that add up to a target, or {-1, -1} if there are none. Example: {2, 7, 11, 15}, target 9 → {0, 1}.
Show hint
For each number, the partner you need is target - n. An unordered_map from value to index answers "have I seen it?" in O(1).
Show solution
#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
std::pair<int, int> two_sum(const std::vector<int>& nums, int target) {
std::unordered_map<int, int> seen; // value -> index
for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
if (auto it = seen.find(target - nums[i]); it != seen.end()) {
return {it->second, i};
}
seen[nums[i]] = i;
}
return {-1, -1};
}
int main() {
for (auto [a, b] : {two_sum({2, 7, 11, 15}, 9), two_sum({3, 2, 4}, 6), two_sum({1, 2}, 10)}) {
std::cout << a << ',' << b << ' ';
}
std::cout << '\n';
}0,1 1,2 -1,-1O(n) time, O(n) space. Checking every pair would be O(n²).
Challenge 2: Valid Parentheses#
Valid Parentheses
Given a string of ()[]{}, return whether every bracket is closed in the correct order. "{[()]}" is valid; "([)]" is not.
Show hint
Push opening brackets onto a stack; each closing bracket must match the top.
Show solution
#include <iostream>
#include <stack>
#include <string>
bool is_valid(const std::string& s) {
std::stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
char open = c == ')' ? '(' : c == ']' ? '[' : '{';
if (st.empty() || st.top() != open) return false;
st.pop();
}
}
return st.empty();
}
int main() {
std::cout << std::boolalpha;
for (const char* s : {"{[()]}", "([)]", "((", ""}) {
std::cout << is_valid(s) << ' ';
}
std::cout << '\n';
}true false false trueO(n) time, O(n) space.
Challenge 3: Reverse the Words in a Sentence#
Reverse Words
Reverse the order of words in " the sky is blue ", giving "blue is sky the" with single spaces.
Show hint
Reading with >> from a std::istringstream skips extra spaces for you.
Show solution
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::string reverse_words(const std::string& s) {
std::istringstream in(s);
std::vector<std::string> words;
std::string w;
while (in >> w) words.push_back(w);
std::string result;
for (auto it = words.rbegin(); it != words.rend(); ++it) {
if (!result.empty()) result += ' ';
result += *it;
}
return result;
}
int main() {
std::cout << '[' << reverse_words(" the sky is blue ") << "]\n";
}[blue is sky the]O(n) time and space.
Challenge 4: Valid Anagram#
Valid Anagram
Return whether two lowercase strings are anagrams (same letters, same counts). "listen" / "silent" → true.
Show hint
Count letters in an array of 26 integers: add for one string, subtract for the other.
Show solution
#include <array>
#include <iostream>
#include <string>
bool is_anagram(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return false;
std::array<int, 26> count{};
for (std::size_t i = 0; i < a.size(); ++i) {
++count[a[i] - 'a'];
--count[b[i] - 'a'];
}
for (int c : count) {
if (c != 0) return false;
}
return true;
}
int main() {
std::cout << std::boolalpha << is_anagram("listen", "silent") << ' '
<< is_anagram("rat", "car") << '\n';
}true falseO(n) time, O(1) space. Sorting both strings and comparing is O(n log n).
Challenge 5: Maximum Subarray Sum#
Maximum Subarray (Kadane)
Find the largest sum of a contiguous subarray. For {-2, 1, -3, 4, -1, 2, 1, -5, 4} the answer is 6 (4, -1, 2, 1).
Show hint
At each position, the best subarray ending here either extends the previous one or starts fresh: current = max(x, current + x).
Show solution
#include <algorithm>
#include <iostream>
#include <vector>
int max_subarray(const std::vector<int>& v) {
int current = v[0];
int best = v[0];
for (std::size_t i = 1; i < v.size(); ++i) {
current = std::max(v[i], current + v[i]);
best = std::max(best, current);
}
return best;
}
int main() {
std::cout << max_subarray({-2, 1, -3, 4, -1, 2, 1, -5, 4}) << ' '
<< max_subarray({-3, -1, -2}) << '\n';
}6 -1O(n) time, O(1) space. Starting best from the first element (not 0) handles all-negative input correctly.
Challenge 6: Merge Two Sorted Arrays#
Merge Sorted Arrays
Merge two sorted vectors into one sorted vector without calling sort.
Show hint
Walk both vectors with two indexes, always taking the smaller current element.
Show solution
#include <iostream>
#include <vector>
std::vector<int> merge(const std::vector<int>& a, const std::vector<int>& b) {
std::vector<int> out;
out.reserve(a.size() + b.size());
std::size_t i = 0;
std::size_t j = 0;
while (i < a.size() && j < b.size()) {
out.push_back(a[i] <= b[j] ? a[i++] : b[j++]);
}
while (i < a.size()) out.push_back(a[i++]);
while (j < b.size()) out.push_back(b[j++]);
return out;
}
int main() {
for (int x : merge({1, 4, 9}, {2, 3, 10, 12})) std::cout << x << ' ';
std::cout << '\n';
}1 2 3 4 9 10 12O(n + m) time. std::merge from <algorithm> does the same.
Challenge 7: Binary Search#
Binary Search
Return the index of target in a sorted vector, or -1. Write it iteratively.
Show hint
Keep a range [low, high]; compare with the middle and discard half. Compute the middle as low + (high - low) / 2.
Show solution
#include <iostream>
#include <vector>
int binary_search(const std::vector<int>& v, int target) {
int low = 0;
int high = static_cast<int>(v.size()) - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (v[mid] == target) return mid;
if (v[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
int main() {
std::vector<int> v = {3, 8, 15, 23, 42, 57, 91};
std::cout << binary_search(v, 42) << ' ' << binary_search(v, 3) << ' ' << binary_search(v, 50) << '\n';
}4 0 -1O(log n) time. Off-by-one errors are the classic trap: use low <= high, and move to mid + 1 / mid - 1.
Challenge 8: Rotate an Array#
Rotate Array
Rotate a vector to the right by k steps in place: {1, 2, 3, 4, 5, 6, 7}, k = 3 → {5, 6, 7, 1, 2, 3, 4}.
Show hint
Reverse the whole vector, then reverse the first k elements and the rest separately.
Show solution
#include <algorithm>
#include <iostream>
#include <vector>
void rotate_right(std::vector<int>& v, std::size_t k) {
if (v.empty()) return;
k %= v.size();
std::reverse(v.begin(), v.end());
std::reverse(v.begin(), v.begin() + k);
std::reverse(v.begin() + k, v.end());
}
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7};
rotate_right(v, 3);
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
}5 6 7 1 2 3 4O(n) time, O(1) extra space. std::rotate(v.begin(), v.end() - k, v.end()) is the library version.
Challenge 9: Longest Substring Without Repeating Characters#
Longest Unique Substring
Return the length of the longest substring without repeating characters. "abcabcbb" → 3 ("abc"); "pwwkew" → 3 ("wke").
Show hint
Use a sliding window [left, right]. Remember the last index of each character; when a repeat appears inside the window, move left just past it.
Show solution
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
int longest_unique(const std::string& s) {
std::array<int, 256> last{};
last.fill(-1);
int best = 0;
int left = 0;
for (int right = 0; right < static_cast<int>(s.size()); ++right) {
unsigned char c = static_cast<unsigned char>(s[right]);
if (last[c] >= left) left = last[c] + 1;
last[c] = right;
best = std::max(best, right - left + 1);
}
return best;
}
int main() {
std::cout << longest_unique("abcabcbb") << ' ' << longest_unique("pwwkew") << ' '
<< longest_unique("bbbb") << ' ' << longest_unique("") << '\n';
}3 3 1 0O(n) time, O(1) space (the table has a fixed 256 entries).
Challenge 10: Reverse a Linked List#
Reverse a Linked List
Reverse a singly linked list built from nodes with value and next, and return the new head.
Show hint
Walk the list once with three pointers: prev, current and next. Turn each current->next around to point at prev.
Show solution
#include <iostream>
#include <memory>
struct Node {
int value;
Node* next;
};
Node* reverse(Node* head) {
Node* prev = nullptr;
while (head) {
Node* next = head->next; // remember the rest
head->next = prev; // turn the link around
prev = head;
head = next;
}
return prev;
}
int main() {
Node n4{4, nullptr};
Node n3{3, &n4};
Node n2{2, &n3};
Node n1{1, &n2};
for (Node* p = reverse(&n1); p; p = p->next) std::cout << p->value << ' ';
std::cout << '\n';
}4 3 2 1O(n) time, O(1) space. The nodes live on the stack here to keep the example short; a real list would allocate nodes with smart pointers or use std::list/std::forward_list.
How to approach a coding interview#
- Clarify: ask about input size, edge cases (empty, duplicates, negatives) and the expected output format.
- Start simple: describe a brute-force solution and its complexity, then improve it.
- Pick a technique: hashing, two pointers, sliding window, stack, binary search, sorting, or dynamic programming cover most problems.
- Write clean code: clear names,
const¶meters, standard containers. - Test out loud with a small example and an edge case before saying you are done.
Finished this lesson?