Find the Most Common Response Problem
#3527
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3527.
You are given a 2D string array responses where each responses[i] is an array of strings representing survey responses from the i^th 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.
Example 1:
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.
Example 2:
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.
Constraints:
1 <= responses.length <= 10001 <= responses[i].length <= 10001 <= responses[i][j].length <= 10responses[i][j]consists of only lowercase English letters
Solution
Approach: Hash Table
Count, for every response, the number of days on which it appears: remove duplicates inside each day's list, then add one to a hash table for each remaining response. Finally scan the table and keep the response with the highest count, using the alphabetically smaller one on ties.
Complexity: O(L) time and O(L) extra space, where L is the total number of responses across all days.
class Solution:
def findCommonResponse(self, responses: List[List[str]]) -> str:
cnt = Counter()
for ws in responses:
for w in set(ws):
cnt[w] += 1
ans = responses[0][0]
for w, x in cnt.items():
if cnt[ans] < x or (cnt[ans] == x and w < ans):
ans = w
return ans