C++ · Module 20 · Lesson 41 min read

STL Coding Interview Problems

The pattern: pick the right container

ProblemKey toolComplexity
Two Sumunordered_map<value, index>O(n)
Group Anagramsunordered_map<sorted word, vector<string>>O(n·k log k)
Top K Frequentcount with unordered_map, then priority_queue / partial_sortO(n log k)
Valid Parenthesesstack<char>O(n)
Merge Intervalssort by start, then sweepO(n log n)
LRU Cachelist (order) + unordered_map<key, list::iterator>O(1) get/put
Longest substring without repeatssliding window + unordered_map<char, last index>O(n)
Kth largestnth_element or min-heap of size kO(n) / O(n log k)
Intersection of arraysunordered_set or sort + two pointersO(n)

LRU cache explained ⭐

  • std::list<std::pair<Key, Value>> keeps items from most to least recently used
  • std::unordered_map<Key, list::iterator> finds an item in O(1)
  • get: move the node to the front with splice (O(1), iterators stay valid)
  • put: update or insert at the front; if over capacity, erase the back

Interview tips

  • State the brute force and its complexity first, then improve
  • Talk about edge cases: empty input, duplicates, negative numbers, ties
  • Prefer clear STL code over clever tricks; name variables well
  • Know the complexity of every container operation you use (Unit 13.8)

Example

C++
#include <algorithm>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

std::pair<int, int> two_sum(const std::vector<int>& v, int target) {
    std::unordered_map<int, int> seen;
    for (int i = 0; i < static_cast<int>(v.size()); ++i) {
        if (auto it = seen.find(target - v[i]); it != seen.end()) return { it->second, i };
        seen[v[i]] = i;
    }
    return { -1, -1 };
}

std::vector<std::vector<std::string>> group_anagrams(const std::vector<std::string>& words) {
    std::unordered_map<std::string, std::vector<std::string>> groups;
    for (const auto& w : words) { std::string key = w; std::sort(key.begin(), key.end()); groups[key].push_back(w); }
    std::vector<std::vector<std::string>> out;
    for (auto& [k, g] : groups) out.push_back(std::move(g));
    std::sort(out.begin(), out.end());                               // deterministic order for display
    return out;
}

std::vector<std::string> top_k(const std::vector<std::string>& words, std::size_t k) {
    std::unordered_map<std::string, int> freq;
    for (const auto& w : words) ++freq[w];
    std::vector<std::pair<std::string, int>> v(freq.begin(), freq.end());
    std::partial_sort(v.begin(), v.begin() + static_cast<long>(std::min(k, v.size())), v.end(), [](const auto& a, const auto& b) {
        return a.second != b.second ? a.second > b.second : a.first < b.first;
    });
    std::vector<std::string> out;
    for (std::size_t i = 0; i < k && i < v.size(); ++i) out.push_back(v[i].first);
    return out;
}

bool valid_parentheses(const std::string& s) {
    std::stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') { st.push(c); continue; }
        if (st.empty()) return false;
        char o = st.top(); st.pop();
        if ((c == ')' && o != '(') || (c == ']' && o != '[') || (c == '}' && o != '{')) return false;
    }
    return st.empty();
}

std::vector<std::pair<int, int>> merge_intervals(std::vector<std::pair<int, int>> iv) {
    std::sort(iv.begin(), iv.end());
    std::vector<std::pair<int, int>> out;
    for (const auto& [s, e] : iv) {
        if (!out.empty() && s <= out.back().second) out.back().second = std::max(out.back().second, e);
        else out.push_back({ s, e });
    }
    return out;
}

class LRUCache {
public:
    explicit LRUCache(std::size_t cap) : cap_(cap) {}
    int get(int key) {
        auto it = pos_.find(key);
        if (it == pos_.end()) return -1;
        items_.splice(items_.begin(), items_, it->second);           // move to front, O(1)
        return it->second->second;
    }
    void put(int key, int value) {
        if (auto it = pos_.find(key); it != pos_.end()) {
            it->second->second = value;
            items_.splice(items_.begin(), items_, it->second);
            return;
        }
        items_.emplace_front(key, value);
        pos_[key] = items_.begin();
        if (items_.size() > cap_) { pos_.erase(items_.back().first); items_.pop_back(); }   // evict LRU
    }
private:
    std::size_t cap_;
    std::list<std::pair<int, int>> items_;
    std::unordered_map<int, std::list<std::pair<int, int>>::iterator> pos_;
};

int main() {
    auto [i, j] = two_sum({ 450, 1200, 300, 800, 1550 }, 2000);
    std::cout << "two_sum -> indexes " << i << " and " << j << '\n';

    std::cout << "anagram groups:";
    for (const auto& g : group_anagrams({ "listen", "save", "silent", "vase", "enlist", "budget" })) {
        std::cout << " [";
        for (std::size_t k = 0; k < g.size(); ++k) std::cout << (k ? " " : "") << g[k];
        std::cout << "]";
    }
    std::cout << '\n';

    std::cout << "top 2 categories:";
    for (const auto& w : top_k({ "food", "rent", "food", "travel", "food", "travel", "fun" }, 2)) std::cout << ' ' << w;
    std::cout << '\n';

    std::cout << std::boolalpha << "valid \"{[()]}\"? " << valid_parentheses("{[()]}")
              << ", \"(]\"? " << valid_parentheses("(]") << '\n';

    std::cout << "merged intervals:";
    for (auto [s, e] : merge_intervals({ { 8, 10 }, { 1, 3 }, { 2, 6 }, { 15, 18 }, { 17, 20 } }))
        std::cout << " [" << s << "," << e << "]";
    std::cout << '\n';

    LRUCache cache(2);
    cache.put(1, 100);
    cache.put(2, 200);
    std::cout << "get(1) = " << cache.get(1);       // 1 becomes most recent
    cache.put(3, 300);                              // evicts 2
    std::cout << ", get(2) = " << cache.get(2) << ", get(3) = " << cache.get(3) << '\n';
    return 0;
}

/* Output:
two_sum -> indexes 1 and 3
anagram groups: [budget] [listen silent enlist] [save vase]
top 2 categories: food travel
valid "{[()]}"? true, "(]"? false
merged intervals: [1,6] [8,10] [15,20]
get(1) = 100, get(2) = -1, get(3) = 300
*/