KatInterview

Find the Most Frequent Character Difference

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingarrays & hashinghash countingstrings

Last updated

Tests whether a candidate can use hash counting to find the pair of distinct characters whose absolute frequency difference is largest in a given string.

Find the Most Frequent Character Difference

You are given a non-empty string s made up of lowercase English letters.

Define the frequency difference of an ordered pair of distinct characters (a, b) (where a != b and both appear in s) as:

freq(a) - freq(b)

where freq(c) is the number of times character c appears in s.

Your task is to find the maximum frequency difference across all valid ordered pairs (a, b), and return the character a that achieves it.

  • If multiple characters a could achieve the same maximum difference (tied most-frequent characters paired against the same least-frequent character), return the one that comes first alphabetically.
  • It is guaranteed that s contains at least 2 distinct characters.

Constraints

  • 1 <= len(s) <= 2000
  • s consists only of lowercase English letters ('a'–'z').
  • s contains at least 2 distinct characters.

Examples

Example 1

Input: most_frequent_char_diff('aabbbbcc')

Output: 'b'

Example 2

Input: most_frequent_char_diff('abcabc')

Output: 'a'

Example 3

Input: most_frequent_char_diff('aaabbc')

Output: 'a'

Hints

Hint 1

Count the frequency of every character in the string using a dictionary or Counter.

Hint 2

The maximum frequency difference is simply max_freq - min_freq, where max_freq and min_freq are the highest and lowest frequencies among all characters that appear in s.

Hint 3

If multiple characters share the maximum frequency, return the alphabetically smallest one (standard min() over a list of tied characters).