I need to transpose a square matrix that's represented by a char array. Is there a way to perform it in less than o(n^2) complexity? Anyway, what's the most cache-efficient way to do it?
3 Answers
No, you can not make it in less then O(n^2) and the reason behind this is that you need to at least touch each element in the matrix once (which is already (n*n). Therefore you can not do better.
The best you can do is to use O(1) additional memory (not time) doing in-place matrix transpose (which is nicely outlined in wikipedia).
Note that you do not always need to calculate transpose matrix. For a lot of applications you can just swap coordinates (if you need A[i][j] - just return A[j][i] -th element)
Comments
This will always take O(NM), since you have to calculate the corresponding transpose coordinate for every element:
// char matrix[N * M]
// char transpose[N * M]
for(int i = 0; i < N*M; i++)
transpose[i] = matrix[ (M * (i % N)) + (i / N) ];
If you are doing this with NxN matrices, then it will take O(n^2) to calculate the transpose. If you don't need to store the transpose, you could just iterate over it while inverting your indexes and effectively do the same thing without additional memory.