Drill

ProblemsC++ › data

Interleave two lists

easydataTwo pointersArraysC++

Two queues for two registers are interleaved so every other customer comes from each.

alternatingMerge(first: list<int>, second: list<int>) → list<int>

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

std::vector<int> alternatingMerge(std::vector<int> first, std::vector<int> second) {
    
}

Worked examples

CallResult
alternatingMerge(std::vector<int>{1, 2, 3}, std::vector<int>{9})std::vector<int>{1, 9, 2, 3}
alternatingMerge(std::vector<int>{1}, std::vector<int>{4, 5})std::vector<int>{1, 4, 5}
alternatingMerge(std::vector<int>{1, 2}, std::vector<int>{3, 4})std::vector<int>{1, 3, 2, 4}
alternatingMerge(std::vector<int>{}, std::vector<int>{1, 2})std::vector<int>{1, 2}

Hint

Loop up to the longer length and take each element that still exists.

Reference solution in C++
std::vector<int> alternatingMerge(std::vector<int> first, std::vector<int> second) {
    std::vector<int> result;
    int n = (int) first.size();
    if ((int) second.size() > n) n = (int) second.size();
    for (int i = 0; i < n; i++) {
        if (i < (int) first.size()) result.push_back(first[i]);
        if (i < (int) second.size()) result.push_back(second[i]);
    }
    return result;
}

The same problem in another language

More data problems in C++