KatInterview

Find All Top-Frequency Labels Without Using max()

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashinghash-mapcountingfrequency

Last updated

Count items by their string form and return every label tied for the highest count, in first-appearance order, without calling max().

Top-Frequency Labels

You are given a list of items, which may be of mixed types. Convert each item to text with Python's str() and count how many times each resulting text label occurs. Return all labels that occur the most often.

Write a function that takes the list and returns the list of labels with the highest count.

Rules

  • Every item is converted with str(item) before counting, so counting is case-sensitive. For example, "park" and "Park" are different labels. Values of different types that produce the same text, such as 1 and "1", count as the same label.
  • If several labels share the highest count, return all of them.
  • Labels in the result must appear in order of their first appearance in the input list.
  • If the input list is empty, return an empty list.
  • You may not use the built-in max() function. Find the highest count yourself.
  • The return value is a list of strings.

Constraints

  • 0 <= len(items) <= 10^5
  • Each item can be converted to text with str().
  • Do not use max().

Examples

Example 1

Input: top_frequency_labels(['park', 'Park', 'McDonalds', 'apple', 'Apple Park', 'park', 'Park'])

Output: ['park', 'Park']

Example 2

Input: top_frequency_labels(['a', 'b', 'a', 'c', 'b'])

Output: ['a', 'b']

Example 3

Input: top_frequency_labels([])

Output: []

Hints

Hint 1

Build a dictionary that maps each text label to the number of times it occurs. Python dictionaries remember insertion order, which helps with the ordering rule.

Hint 2

Replace max() with a loop: keep a variable for the highest count seen so far and update it whenever you see a larger count.

Hint 3

Once you know the highest count, make a second pass over the dictionary and collect every label whose count equals it. An empty input leaves the highest count at 0 and no labels are collected, so it returns [].