You are given a 2D string array responses where each responses[i] is an array of strings representing survey responses from the ith day.
Return the most common response across all days after removing
duplicate responses within each responses[i]. If there is a tie, return the lexicographically smallest response.
Input: responses =[["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]]Output: "good"Explanation:
* After removing duplicates within each list,`responses = [["good", "ok"], ["ok", "bad", "good"], ["good"], ["bad"]]`.*`"good"` appears 3 times,`"ok"` appears 2 times, and `"bad"` appears 2 times.* Return `"good"` because it has the highest frequency.
Input: responses =[["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]Output: "bad"Explanation:
* After removing duplicates within each list we have `responses = [["good", "ok"], ["ok", "bad"], ["bad", "notsure"], ["great", "good"]]`.*`"bad"`,`"good"`, and `"ok"` each occur 2 times.* The output is`"bad"` because it is the lexicographically smallest amongst the words with the highest frequency.
To find the most common response, first remove duplicates within each day’s responses, then count the frequency of each unique response across all days. In case of a tie, return the lexicographically smallest response.
classSolution {
public String mostCommonResponse(List<List<String>> responses) {
Map<String, Integer> cnt =new HashMap<>();
for(List<String> day : responses) {
Set<String> seen =new HashSet<>(day);
for(String resp : seen) cnt.put(resp, cnt.getOrDefault(resp, 0)+1);
}
String ans ="";
int mx = 0;
for(var e : cnt.entrySet()) {
String resp = e.getKey(); int c = e.getValue();
if(c > mx || (c == mx && (ans.equals("") || resp.compareTo(ans) < 0))) {
mx = c;
ans = resp;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funmostCommonResponse(responses: List<List<String>>): String {
val cnt = mutableMapOf<String, Int>()
for (day in responses) {
val seen = day.toSet()
for (resp in seen) cnt[resp] = cnt.getOrDefault(resp, 0) + 1 }
var ans = ""var mx = 0for ((resp, c) in cnt) {
if (c > mx || (c == mx && (ans ==""|| resp < ans))) {
mx = c
ans = resp
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defmostCommonResponse(self, responses: list[list[str]]) -> str:
from collections import Counter
cnt = Counter()
for day in responses:
for resp in set(day):
cnt[resp] +=1 mx = max(cnt.values())
return min([resp for resp, c in cnt.items() if c == mx])
use std::collections::{HashMap, HashSet};
impl Solution {
pubfnmost_common_response(responses: Vec<Vec<String>>) -> String {
letmut cnt = HashMap::new();
for day in responses {
let seen: HashSet<_>= day.iter().collect();
for resp in seen {
*cnt.entry(resp).or_insert(0) +=1;
}
}
letmut ans = String::new();
letmut mx =0;
for (resp, &c) in&cnt {
if c > mx || (c == mx && (ans.is_empty() || resp <&ans)) {
mx = c;
ans = resp.clone();
}
}
ans
}
}