Drill

ProblemsC++ › patterns

Turn the rows into columns

easypatternsGridsArraysC++

An export writes a table row by row, and the spreadsheet on the other end wants it the other way round.

transpose(table: list<list<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>> transpose(std::vector<std::vector<int>> table) {
    
}

Worked examples

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

Hint

The result has one row per original column. Walk the columns on the outside and the rows on the inside.

Reference solution in C++
std::vector<std::vector<int>> transpose(std::vector<std::vector<int>> table) {
    std::vector<std::vector<int>> flipped;
    if (table.empty()) return flipped;
    for (size_t c = 0; c < table[0].size(); c++) {
        std::vector<int> row;
        for (size_t r = 0; r < table.size(); r++) row.push_back(table[r][c]);
        flipped.push_back(row);
    }
    return flipped;
}

The same problem in another language

More patterns problems in C++