Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Print a matrix in spiral order (clockwise from the top-left).

Problem: Print a matrix in spiral order (clockwise from the top-left).
vector<int> spiral(vector<vector<int>>& m) {
    vector<int> out;
    int top = 0, bot = m.size() - 1, l = 0, r = m[0].size() - 1;
    while (top <= bot && l <= r) {
        for (int c = l; c <= r; c++) out.push_back(m[top][c]); top++;
        for (int i = top; i <= bot; i++) out.push_back(m[i][r]); r--;
        if (top <= bot) { for (int c = r; c >= l; c--) out.push_back(m[bot][c]); bot--; }
        if (l <= r) { for (int i = bot; i >= top; i--) out.push_back(m[i][l]); l++; }
    }
    return out;
}
// m = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}
What does spiral(m) contain, in order?
  1. A. 1 2 3 4 8 12 11 10 9 5 6 7 6
  2. B. 1 2 3 4 8 12 11 10 9 5 6 7
  3. C. 1 2 3 4 8 12 11 10 9 5 7 6
  4. D. 1 2 3 4 5 6 7 8 9 10 11 12

Correct answer: B. 1 2 3 4 8 12 11 10 9 5 6 7

Peel the boundary layer by layer. The guards 'if (top <= bot)' and 'if (l <= r)' stop the last row or column from being printed twice in non-square matrices (without them 6 would repeat). O(R·C).

More Coding Interview Problems questions

Exams that ask this topic