April 17th, 2009, 4:47 pm
I recently got asked this question during a phone interview:Suppose you have a n x m matrix stored in an one dimensional array in column-major order, that is, element (i,j) in the matrix is at position i+j*n in the one dimensional array. Write an algorithm that transposes the matrix in-place.According to the interviewer, you should do this "without allocating an amount of memory of the same order as the matrix". Is it possible to do this without keeping a tab of which elements we already touched? What I mean is the following:We know element (i,j) in the original matrix (position i+n*j in the array) goes to element (j,i) in the transposed matrix (position j+i*m in the array). In turn, j+i*m is the position of element (k,l) in the original matrix where k=a mod n, and l=(a-k)/n. If one loops over this sequence it'll eventually go back to element (i,j). Without keeping a tab of the elements we already transposed, how do I know which element to proceed with after a cycle is taken care of?My initial approach would be storing a bit array of size n*m and setting each element to 1 after being visited on the scheme above, but this array is clearly "of the same order as the matrix".ps. this is not a problem for square matrices (n x n) since element (i,j) = i+j*n goes to (j,i) = j+i*n, which in turn goes to the original i+j*n. That is, for square matrices this is done easily by swapping each element on the upper triangular with the corresponding element on the lower triangular.