Leetcode 3019. Number of Changing Keys
You are given a list of keys where each key is represented as a list of characteristics. Two keys are considered identical if they have exactly the same characteristics in any order. The task is to determine how many keys need to be changed to make all keys identical.
To determine the number of keys which need to be changed to make all keys identical, we can approach the problem as follows:
import java.util.*;
public class ChangingKeys {
public static int numberOfChangingKeys(List<List<String>> keys) {
if (keys == null || keys.isEmpty()) return 0;
// Map to store the frequency of each normalized key
Map<List<String>, Integer> keyCountMap = new HashMap<>();
for (List<String> key : keys) {
// Sort characteristics to standardize the representation
List<String> sortedKey = new ArrayList<>(key);
Collections.sort(sortedKey);
keyCountMap.put(sortedKey, keyCountMap.getOrDefault(sortedKey, 0) + 1);
}
// Find the maximum frequency
int maxFrequency = 0;
for (int count : keyCountMap.values()) {
maxFrequency = Math.max(maxFrequency, count);
}
// Number of keys to change is total keys minus the most frequent key count
return keys.size() - maxFrequency;
}
public static void main(String[] args) {
List<List<String>> keys = Arrays.asList(
Arrays.asList("A", "B", "C"),
Arrays.asList("C", "B", "A"),
Arrays.asList("A", "B"),
Arrays.asList("B", "C", "B")
);
System.out.println(numberOfChangingKeys(keys)); // Example usage
}
}
Combining these, the overall time complexity is (O(N \cdot M \log M)).
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?