Autocoder

C++ Coding Interview Questions

Last updated 2026-11-19

This page is a set of C++ coding problems that cover what technical rounds ask when they want to see you write real code: string and array manipulation, a linked list, small class implementations and STL usage. Each answer gives the idea, the complexity and a short C++17 solution, so you can compare it with your own.

The goal is not to memorise the code but to see the pattern: a two-pointer pass, a hash map for counting, a sentinel node, a fast exponent loop. For pattern-by-pattern practice, use the DSA interview question pages and the strategy in how to crack a DSA coding round.

LanguageC++17
FormatProblem, idea, code, complexity
NeedsBasic STL knowledge

Habits that score marks in a C++ coding round

Edge cases to mention every time

Empty input, a single element, duplicates, negative numbers, integer overflow and the case where no answer exists. Naming them before you code shows that you read the problem as an engineer, and it often pre-empts the interviewer's follow-up.

C++ Coding Interview Questions: questions with worked answers

  1. 1

    Reverse a string in place without extra memory.

    easy

    Use two indices from both ends and swap until they meet. Time O(n), space O(1). For C++ interviews, mention that std::reverse(s.begin(), s.end()) does the same, and that the loop must use an unsigned-safe condition.

    cpp
    void reverseStr(std::string& s) {
        for (size_t i = 0, j = s.size(); i + 1 < j; ++i, --j)
            std::swap(s[i], s[j - 1]);
    }
  2. 2

    Check whether a string is a palindrome, ignoring case and non-alphanumeric characters.

    easy

    Two pointers that skip non-alphanumeric characters and compare lower-cased characters. Cast to unsigned char before calling isalnum or tolower, because passing a negative char is undefined behaviour. Time O(n), space O(1).

    cpp
    bool isPal(const std::string& s) {
        int i = 0, j = (int)s.size() - 1;
        while (i < j) {
            while (i < j && !std::isalnum((unsigned char)s[i])) ++i;
            while (i < j && !std::isalnum((unsigned char)s[j])) --j;
            if (std::tolower((unsigned char)s[i]) != std::tolower((unsigned char)s[j])) return false;
            ++i; --j;
        }
        return true;
    }
  3. 3

    Find the first non-repeating character in a string.

    easy

    Count frequencies in an array of 256 (or 26 for lowercase) in one pass, then scan again for the first count of one. Time O(n), space O(1) because the alphabet is fixed. Return -1 or a sentinel when none exists.

    cpp
    int firstUnique(const std::string& s) {
        int cnt[256] = {};
        for (unsigned char ch : s) ++cnt[ch];
        for (size_t i = 0; i < s.size(); ++i)
            if (cnt[(unsigned char)s[i]] == 1) return (int)i;
        return -1;
    }
  4. 4

    Two Sum: return indices of two numbers adding to a target.

    medium

    Store each seen value and its index in an unordered_map. For each x, check whether target - x is already in the map. Time O(n) average, space O(n). The brute force is O(n squared); sorting with two pointers loses the original indices unless you pair them first.

    cpp
    std::vector<int> twoSum(const std::vector<int>& a, int target) {
        std::unordered_map<int,int> seen;
        for (int i = 0; i < (int)a.size(); ++i) {
            auto it = seen.find(target - a[i]);
            if (it != seen.end()) return {it->second, i};
            seen[a[i]] = i;
        }
        return {};
    }
  5. 5

    Reverse a singly linked list, iteratively.

    medium

    Walk the list keeping prev, cur and next: save next, point cur->next at prev, then advance both. Time O(n), space O(1). A common slip is losing the rest of the list by overwriting next before saving it. The recursive version uses O(n) stack.

    cpp
    struct Node { int val; Node* next; };
    Node* reverse(Node* head) {
        Node* prev = nullptr;
        while (head) {
            Node* nxt = head->next;
            head->next = prev;
            prev = head;
            head = nxt;
        }
        return prev;
    }
  6. 6

    Detect a cycle in a linked list and find where it starts.

    medium

    Floyd's algorithm: move slow by one and fast by two; if they meet there is a cycle. To find the start, reset one pointer to the head and move both by one until they meet, and the meeting node is the cycle start. This works because the distance from the head to the cycle start equals the distance from the meeting point to the start, modulo the cycle length. Time O(n), space O(1).

    cpp
    Node* cycleStart(Node* head) {
        Node *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next; fast = fast->next->next;
            if (slow == fast) {
                slow = head;
                while (slow != fast) { slow = slow->next; fast = fast->next; }
                return slow;
            }
        }
        return nullptr;
    }
  7. 7

    Implement fast exponentiation (pow with modulus).

    medium

    Binary exponentiation squares the base and halves the exponent, multiplying into the result when the current bit is set. Time O(log e). Use long long and reduce modulo at each step; with a modulus near 10^9 the product of two residues fits in a 64-bit signed integer, but with larger moduli it needs __int128.

    cpp
    long long power(long long b, long long e, long long mod) {
        long long r = 1; b %= mod;
        while (e > 0) {
            if (e & 1) r = r * b % mod;
            b = b * b % mod;
            e >>= 1;
        }
        return r;
    }
  8. 8

    Merge two sorted arrays into one sorted vector.

    medium

    Use two pointers and always take the smaller front element; append the leftover tail. Time O(n + m), space O(n + m) for the output. Use <= when comparing so the merge is stable. This is the merge step of merge sort.

    cpp
    std::vector<int> mergeSorted(const std::vector<int>& a, const std::vector<int>& b) {
        std::vector<int> r; r.reserve(a.size() + b.size());
        size_t i = 0, j = 0;
        while (i < a.size() && j < b.size()) r.push_back(a[i] <= b[j] ? a[i++] : b[j++]);
        while (i < a.size()) r.push_back(a[i++]);
        while (j < b.size()) r.push_back(b[j++]);
        return r;
    }
  9. 9

    Maximum subarray sum (Kadane's algorithm).

    medium

    Keep the best sum of a subarray ending at the current index: cur = max(a[i], cur + a[i]), and track the global best. Initialise both from the first element, not from zero, so all-negative arrays return the largest (least negative) element. Time O(n), space O(1).

    cpp
    int maxSub(const std::vector<int>& a) {
        int cur = a[0], best = a[0];
        for (size_t i = 1; i < a.size(); ++i) {
            cur = std::max(a[i], cur + a[i]);
            best = std::max(best, cur);
        }
        return best;
    }
  10. 10

    Implement a stack that returns the minimum in O(1).

    medium

    Keep a second stack of running minimums, or store pairs of (value, min so far) in one stack. push computes min(value, current min), pop removes both, getMin reads the top. All operations are O(1) and space is O(n). Test with duplicates of the minimum: pop must not lose the min.

    cpp
    class MinStack {
        std::vector<std::pair<int,int>> st; // value, min so far
    public:
        void push(int x) { st.push_back({x, st.empty() ? x : std::min(x, st.back().second)}); }
        void pop() { st.pop_back(); }
        int top() const { return st.back().first; }
        int getMin() const { return st.back().second; }
    };
  11. 11

    Implement an LRU cache with O(1) get and put.

    hard

    Combine a doubly linked list (most recent at the front) and an unordered_map from key to list iterator. get moves the node to the front with list::splice, which keeps iterators valid and runs in O(1). put updates or inserts at the front and evicts the back when over capacity. This is the standard design-class question for C++ rounds.

    cpp
    class LRU {
        size_t cap;
        std::list<std::pair<int,int>> items;
        std::unordered_map<int, std::list<std::pair<int,int>>::iterator> pos;
    public:
        explicit LRU(size_t 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 (items.size() == cap) { pos.erase(items.back().first); items.pop_back(); }
            items.emplace_front(k, v);
            pos[k] = items.begin();
        }
    };
  12. 12

    Check whether two strings are anagrams.

    medium

    Two strings are anagrams if their character counts match. Count with an array, incrementing for the first string and decrementing for the second, and verify all zeros. Time O(n), space O(1). Sorting both is O(n log n) and simpler. Mention a length check first and that Unicode needs a map rather than a 256 array.

    cpp
    bool anagram(const std::string& a, const std::string& b) {
        if (a.size() != b.size()) return false;
        int cnt[256] = {};
        for (size_t i = 0; i < a.size(); ++i) { ++cnt[(unsigned char)a[i]]; --cnt[(unsigned char)b[i]]; }
        return std::all_of(std::begin(cnt), std::end(cnt), [](int x){ return x == 0; });
    }
  13. 13

    Count set bits in an integer.

    medium

    Brian Kernighan's method: n &= n - 1 clears the lowest set bit, so the loop runs once per set bit. Time O(k) for k set bits. In C++20 use std::popcount from <bit>, and __builtin_popcount on GCC and Clang. For negative signed values, convert to unsigned first to avoid implementation-defined shifts. See bit manipulation questions.

    cpp
    int popcount(unsigned n) {
        int c = 0;
        while (n) { n &= n - 1; ++c; }
        return c;
    }
  14. 14

    Given a vector of intervals, merge all overlapping intervals.

    hard

    Sort by start, then sweep: if the next interval starts at or before the current end, extend the end with max; otherwise push the current interval and start a new one. Time O(n log n) for the sort, space O(n). Touching intervals such as [1,2] and [2,3] merge under the usual convention, so confirm it.

    cpp
    std::vector<std::vector<int>> mergeIntervals(std::vector<std::vector<int>> v) {
        std::sort(v.begin(), v.end());
        std::vector<std::vector<int>> r;
        for (auto& iv : v) {
            if (!r.empty() && iv[0] <= r.back()[1]) r.back()[1] = std::max(r.back()[1], iv[1]);
            else r.push_back(iv);
        }
        return r;
    }

Frequently asked questions

Which language is best for coding rounds, C++ or Python?

C++ is faster and gives you STL, but Python is shorter to write. Use the language you can write bug-free quickly, and check the platform time limits.

How do I avoid integer overflow in C++ solutions?

Use long long for sums and products, check constraints before choosing int, and take modulus at each multiplication step.

Do I need to write my own data structures?

Rarely. Know the STL containers, but be ready to implement a linked list, stack, queue or LRU cache when asked for a design question.

How long should a C++ answer take in a coding test?

Aim to state the approach in two minutes and code a clean solution in ten to twenty. The format varies by company, so check the round details in the how to crack guides.

Related guides

More in Programming Language Interview Questions by Language

See all in this section