cswork / libraryOpen practice workspace

Coding questions · Point72

Determine Most Frequent Product Color in Carts

This question evaluates proficiency in frequency analysis and deterministic tie-breaking for string data, assessing correctness in counting and selection logic.

Scenario

Online store wants to know which color of product appears most frequently in customers’ carts.

Question

Implement a function getMaxColor(colors: List[str]) that returns the color occurring most often; if there is a tie, return the lexicographically smallest color.

Hints

Count frequencies with a hash map, then find max by count and lexicographic order.

Find Most Frequent Cart Color

Given a list of color names representing items in customers' carts, return the color that appears most frequently. If multiple colors share the highest frequency, return the lexicographically smallest color. The list has at least one element.

Constraints

  • 1 <= len(colors) <= 100000
  • Each color is a non-empty string of lowercase English letters (a-z)
  • 1 <= len(color) <= 30
  • Lexicographic order is standard string order (e.g., 'blue' < 'red')

Examples

Example 1

Input: colors = ["red","blue","red","green","blue","red"]
Output: "red"

Explanation: Counts: red=3, blue=2, green=1. Highest frequency is red.

Example 2

Input: colors = ["yellow","blue","blue","red","red","yellow"]
Output: "blue"

Explanation: All have frequency 2; lexicographically smallest is "blue".

Hints

  1. Use a hash map (dictionary) to count occurrences of each color.
  2. Track the best (count, color) pair: prefer higher count, and for ties prefer smaller color.
  3. You can iterate the frequency map once to find the answer in O(k), where k is the number of distinct colors.

Approach

Count each color using a dictionary (Counter). Then scan the (color, count) pairs, tracking the best answer so far. Update when a higher count is found, or when the count ties and the color is lexicographically smaller. This ensures we return the most frequent color with lexicographic tie-breaking.

  • Time complexity: O(n)
  • Space complexity: O(k)