Turn the rows into columns
An export writes a table row by row, and the spreadsheet on the other end wants it the other way round.
- Every row has the same length.
- The value at row r, column c ends up at row c, column r.
- An empty grid comes back empty.
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.
Where you start
std::vector<std::vector<int>> transpose(std::vector<std::vector<int>> table) {
}
Worked examples
| Call | Result |
|---|---|
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;
}