#3527

Find the Most Common Response

Medium
ArrayHash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a HashMap to efficiently count unique responses across all days, ensuring O(n) time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a HashMap to count occurrences of each response.
  2. 2Step 2: For each day's responses, convert to a set to remove duplicates and update counts.
  3. 3Step 3: Find the response with the highest count, resolving ties lexicographically.
solution.py9 lines
1from collections import defaultdict
2
3def most_common_response(responses):
4    count = defaultdict(int)
5    for day in responses:
6        unique_responses = set(day)
7        for response in unique_responses:
8            count[response] += 1
9    return min((response for response in count if count[response] == max(count.values())), key=lambda x: x)

Complexity note: This complexity is efficient due to direct counting and using a set to manage duplicates.

  • 1Using a set efficiently removes duplicates.
  • 2Counting with a HashMap allows for quick frequency checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.