What is the Space complexity of the below code?

Is the space complexity of the below code O(m) or O(n * m). We are creating a vector of size m on each of the n iterations while traversing the matrix. Does this count as O(m) or O(n * m) space (while not considering the space of matrix mat ). Can anyone justify why it is O(m) or O(n * m) or whichever it is?

#include <bits/stdc++.h>
using namespace std;

int main() {
	int n = 5, m = 7;
	vector<vector<int>> mat(n, vector<int>(m));
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> mat[i][j];
	vector<int> v;
	for (int i = 0; i < n; i++) {
		vector<int> row;
		for (int j = 0; j < m; j++) {
	return 0;

Advanced Thanks.

Total Space Complexity: \mathcal{O}(N\times M)
Auxiliary Space Complexity: \mathcal{O}(\max(N,M))


@cubefreak777 thanks

1 Like