Leetcode 2946. Matrix Similarity After Cyclic Shifts
Given a 2D integer matrix grid
, the task is to determine the minimum number of cells that need to be changed to make the matrix similar after any number of cyclical shifts of its rows or columns. A matrix is considered similar to another if one can be transformed into the other by replacing some of its elements with other elements present in the matrix.
With typical constraint ranges in mind, let’s proceed.
Below, I’ll provide the Java solution to address the problem statement:
import java.util.HashMap;
import java.util.Map;
public class MatrixSimilarity {
public int minChangesToMakeSimilar(int[][] grid) {
int rowCount = grid.length;
int colCount = grid[0].length;
// Initialize a hash map to store frequencies of each element in the matrix
Map<Integer, Integer> freqMap = new HashMap<>();
// Populate the frequency map
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < colCount; c++) {
freqMap.put(grid[r][c], freqMap.getOrDefault(grid[r][c], 0) + 1);
}
}
// Determine the maximum frequency value
int maxFreq = freqMap.values().stream().max(Integer::compare).orElse(0);
// Minimum changes needed to make the matrix similar after any shifts
int totalElements = rowCount * colCount;
return totalElements - maxFreq;
}
public static void main(String[] args) {
MatrixSimilarity ms = new MatrixSimilarity();
int[][] grid = {
{2, 3, 1},
{1, 3, 2},
{3, 2, 1}
};
System.out.println(ms.minChangesToMakeSimilar(grid)); // Should output the minimal number of changes needed
}
}
The overall time complexity is (O(n \times m + k)), which is efficient for typical problem constraints.
The space complexity is (O(k)), which is the space needed to store frequencies of unique elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?