You are viewing a single comment's thread. Return to all comments →
Java an time complexity is: O(n) + O(n) + O(n) = O(n)
public static String isValid(String s) { Map<Character, Integer> freqMap = new HashMap<>(); for (char c : s.toCharArray()) { freqMap.put(c, freqMap.getOrDefault(c, 0) + 1); } Map<Integer, Integer> freqOfFreqMap = new HashMap<>(); for (int freq : freqMap.values()) { freqOfFreqMap.put(freq, freqOfFreqMap.getOrDefault(freq, 0) + 1); } if (freqOfFreqMap.size() == 1) { return "YES"; } else if (freqOfFreqMap.size() == 2) { int f1 = (int) freqOfFreqMap.keySet().toArray()[0]; int f2 = (int) freqOfFreqMap.keySet().toArray()[1]; if ((freqOfFreqMap.get(f1) == 1 && (f1 - 1 == f2 || f1 == 1)) || (freqOfFreqMap.get(f2) == 1 && (f2 - 1 == f1 || f2 == 1))) { return "YES"; } } return "NO"; }
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and the Valid String
You are viewing a single comment's thread. Return to all comments →
Java an time complexity is: O(n) + O(n) + O(n) = O(n)