Given a matrix with N rows and M columns, print all elements column by column from top to bottom.
Example 1
Input: mat = [[1, 2, 3], [4, 5, 6]]
Output: 1 4 2 5 3 6
Explanation: First column prints as 1 4, second column prints as 2 5, and third column prints as 3 6.
Example 2
Input: mat = [[10, 20], [30, 40], [50, 60]]
Output: 10 30 50 20 40 60
Explanation: Traversal prints each column from top to bottom before moving right to the next column.
Approach
This approach prints the matrix one column at a time. The outer loop selects each column, while the inner loop traverses all rows in that column from top to bottom. Every element is printed as soon as it is visited, so no extra space is required.
Algorithm
Find the number of rows and columns in the matrix, as these define the boundaries for our traversal.
For column-wise traversal, use an outer loop to access each column one by one.
Use an inner loop for the rows, which makes sure every element within the current column is accessed from top to bottom.
Print the current element as soon as it is accessed, since we want the elements in the same order as they appear in each column.
Continue until all columns and their corresponding rows have been processed.
Dry Run
col wise print
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Function to print matrix elements by column. void printColumnWise(vector<vector<int>>& mat) { // Store total number of rows. int n = mat.size(); // Handle an empty matrix. if (n == 0) { cout << "\n"; return; } // Store total number of columns. int m = mat[0].size(); // Track first printed value for spacing. bool first = true; // Traverse every column from left to right. for (int col = 0; col < m; col++) { // Traverse every row from top to bottom. for (int row = 0; row < n; row++) { // Print a space before every value except the first. if (!first) { cout << " "; } // Print the current matrix element. cout << mat[row][col]; // Mark first value as printed. first = false; } } // Move output cursor to the next line. cout << "\n"; }};// Driver code.int main() { vector<vector<int>> mat = {{1, 2, 3}, {4, 5, 6}}; Solution sol; sol.printColumnWise(mat); return 0;}Complexity Analysis
Time Complexity: O(N × M), traversal visits every matrix cell exactly once.
Space Complexity: O(1), only loop variables are used apart from output handling.
Interview follow-up Questions
Yes. One loop selects each column, and another loop scans each row inside the selected column.
Be the first to add a comment.