easyStringsPattern: Frequency Map

Fascinating Frequency String Solution

Problem Statement

Given a string s consisting of lowercase English letters, determine if all characters that appear in the string have a unique number of occurrences. Return true if the occurrence count of each unique character is distinct, or false otherwise.

Examples

Example 1:
Input:s = "aaabbc"
Output:true
Explanation: The character 'a' occurs 3 times, 'b' occurs 2 times, and 'c' occurs 1 time. The set of frequencies is {3, 2, 1}, and since all frequencies are distinct, we return true.
Example 2:
Input:s = "abacbc"
Output:false
Explanation: The character 'a' occurs 2 times, 'b' occurs 2 times, and 'c' occurs 2 times. The frequencies are not unique because the frequency 2 is repeated.

Constraints

  • 1 <= s.length <= 1000
  • s consists only of lowercase English letters.
Time: O(N) Space: O(1)
First, iterate through the string to build a frequency map of all characters. Then, insert these frequencies into a hash set. If the size of the hash set is equal to the size of the frequency map, it means all frequencies are unique. This runs in O(N) time and O(1) space since there are at most 26 unique lowercase English letters.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.