Search code examples
javamultidimensional-arrayarraylistcollectionstranspose

Transpose of a square matrix using ArrayList with Collections.swap and space Complexity O(1) in Java


Given an 2D square matrix here i'm trying to print a transpose of a matrix with space complexity SC:O(1).

for(int row = 0; row < originalArray.size(); row++) {
    for(int col = row+1; col < originalArray.get(0).size(); col++) {
        Collections.swap(originalArray,originalArray.get(row).get(col),originalArray.get(col).get(row));
    }
}

with temp variable the code works fine but with collections.swap throwing an exception.why Collections API fail here? enter image description here


Solution

  • It is impossible to do using two-dimensional array and Collection.swap(). Because it takes List<?> as an argument. Therefore it may accept a list of rows or a single row, but not the matrix itself.

    However you can represent the matrix as a one-dimensional array and the code will look like:

    for (int row = 0; row < size; row++) {
        for (int col = row + 1; col < size; col++) {
            Collections.swap(list, row * size + col, col * size + row);
        }
    }