Leetcode 1941. Check if All Characters Have Equal Number of Occurrences
Given a string s
, determine if all characters have the same frequency of occurrence in the string.
s
always non-empty?s
?Assuming the input string s
can contain only lowercase English letters and has a maximum length of 105
.
'a', 'b', 'c'
all appear 2 times)'a'
appears 3 times while 'b'
appears 2 times)import java.util.HashMap;
public class Solution {
public boolean areOccurrencesEqual(String s) {
// Step 1: Count frequency of each character
HashMap<Character, Integer> frequencyMap = new HashMap<>();
for (char c : s.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
// Step 2: Check if all frequencies are the same
int frequency = -1; // Initialize to a value that no frequency will have.
for (int count : frequencyMap.values()) {
if (frequency == -1) {
frequency = count; // Set the frequency upon encountering the first entry
} else if (frequency != count) {
return false; // If any frequency doesn't match, return false
}
}
return true; // All frequencies matched
}
}
O(n)
, where n
is the length of the string. Each character is processed once to count frequencies and then verified.O(1)
, since the HashMap will at most store counts for 26 different characters (assuming the input consists exclusively of lowercase English letters).The provided solution efficiently counts character frequencies and checks for equality. The time complexity ensures scalability for large input sizes within the given constraints.
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?