Skip to content

3527. Find the Most Common Response 👍

  • Time: $O(\Sigma |\texttt{responses[i]}|)$
  • Space: $O(\Sigma |\texttt{responses[i]}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  string findCommonResponse(vector<vector<string>>& responses) {
    string ans;
    unordered_map<string, int> count;
    int maxFreq = 0;

    for (const vector<string>& response : responses)
      for (const string& response :
           unordered_set<string>{response.begin(), response.end()})
        ++count[response];

    for (const pair<const string, int>& entry : count)
      maxFreq = max(maxFreq, entry.second);

    for (const auto& [response, freq] : count)
      if (freq == maxFreq && (ans.empty() || response < ans))
        ans = response;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public String findCommonResponse(List<List<String>> responses) {
    String ans = "";
    Map<String, Integer> count = new HashMap<>();
    int maxFreq = 0;

    for (List<String> response : responses)
      for (final String r : new HashSet<>(response))
        count.merge(r, 1, Integer::sum);

    for (final int freq : count.values())
      maxFreq = Math.max(maxFreq, freq);

    for (Map.Entry<String, Integer> entry : count.entrySet()) {
      final String response = entry.getKey();
      final int freq = entry.getValue();
      if (freq == maxFreq && (ans.isEmpty() || response.compareTo(ans) < 0))
        ans = response;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def findCommonResponse(self, responses: list[list[str]]) -> str:
    count = collections.Counter()

    for response in responses:
      for response in set(response):
        count[response] += 1

    maxFreq = max(count.values())
    return min([response
                for response, count in count.items()
                if count == maxFreq])