LeetCode 2946: Matrix Similarity After Cyclic Shifts Solution
Master LeetCode problem 2946 (Matrix Similarity After Cyclic Shifts), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2946. Matrix Similarity After Cyclic Shifts
Problem Explanation
Explanation:
To solve this problem, we need to simulate the process of cyclically shifting rows in the matrix k times. We can achieve this by performing the following steps:
- Iterate
ktimes. - For each iteration, determine whether the row is even or odd based on its index.
- Perform cyclic shifts to the left for even-indexed rows and to the right for odd-indexed rows.
- After all iterations, compare the final modified matrix with the original matrix to check for similarity.
Time Complexity: O(m * n * k) where m is the number of rows, n is the number of columns, and k is the number of shifts. Space Complexity: O(m * n) for storing the matrix.
: :
Solution Code
class Solution {
public boolean isSimilar(int[][] mat, int k) {
int m = mat.length;
int n = mat[0].length;
int[][] original = new int[m][n];
for (int i = 0; i < m; i++) {
original[i] = mat[i].clone();
}
for (int shift = 0; shift < k; shift++) {
int[][] temp = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i % 2 == 0) {
temp[i][(j + 1) % n] = mat[i][j];
} else {
temp[i][j] = mat[i][(j + n - 1) % n];
}
}
}
mat = temp;
}
for (int i = 0; i < m; i++) {
if (!Arrays.equals(original[i], mat[i])) {
return false;
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2946 (Matrix Similarity After Cyclic Shifts)?
This page provides optimized solutions for LeetCode problem 2946 (Matrix Similarity After Cyclic Shifts) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2946 (Matrix Similarity After Cyclic Shifts)?
The time complexity for LeetCode 2946 (Matrix Similarity After Cyclic Shifts) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2946 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2946 in Java, C++, or Python.