Interview Q&A · C++ · 10 questions in this topic

Common Coding Tasks — C++ Interview Q&A

All C++ topics

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

Example.cppcpp
#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

Example.cppcpp
#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

Example.cppcpp
#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;
}

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits