← Back to Home

array


Index Access

2946. Matrix Similarity After Cyclic Shifts

You are given a 0-indexed m x n integer matrix mat and an integer k.
You have to cyclically right shift odd indexed rows k times and cyclically left shift even indexed rows k times.

Return true if the initial and final matrix are exactly the same and false otherwise.

Don't need to shift. Just access the location where it would be if shifted

public boolean areSimilar(int[][] mat, int k) {
    int R = mat.length, C = mat[0].length;
    for(int r = 0; r < R; r++)
        if(r % 2 == 0) {
            for(int c = 0; c < C; c++)
                if(mat[r][c] != mat[r][(c - k + (C * 1000)) % C]) // NEGATIVE INDEX ACCESS
                    return false;
        }
        else {
            for(int c = 0; c < C; c++)
                if(mat[r][c] != mat[r][(c + k) % C]) // POSITIVE INDEX > LEN
                    return false;
        }
    return true;
}

Alternate solution

public boolean areSimilar(int[][] mat, int k) {
    int C = mat[0].length;
    for(var row: mat)
        for(int c = 0; c < C; c++)
            if(row[c] != row[(c + k) % C]) 
                return false;
    return true;
}