Drill

ProblemsC++ › warmup

Break a list into fixed-size pieces

mediumwarmupArraysC++

A bulk API takes at most a hundred records per call, so a long list has to be handed over in pieces.

chunkList(values: list<int>, perChunk: int) → list<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<std::vector<int>> chunkList(std::vector<int> values, int perChunk) {
    
}

Worked examples

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

Hint

Step the index forward by the chunk size and slice, rather than pushing one item at a time.

Reference solution in C++
std::vector<std::vector<int>> chunkList(std::vector<int> values, int perChunk) {
    std::vector<std::vector<int>> result;
    if (perChunk <= 0) return result;
    for (size_t i = 0; i < values.size(); i += perChunk) {
        size_t j = std::min(i + (size_t) perChunk, values.size());
        result.push_back(std::vector<int>(values.begin() + i, values.begin() + j));
    }
    return result;
}

The same problem in another language

More warmup problems in C++