Skip to content

2284. Sender With Largest Word Count 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  string largestWordCount(vector<string>& messages, vector<string>& senders) {
    const int n = messages.size();
    string ans;
    int maxWordsSent = 0;
    unordered_map<string, int> count;  // {sender, the number of words sent}

    for (int i = 0; i < n; ++i) {
      const string& message = messages[i];
      const string& sender = senders[i];
      const int wordsCount = ranges::count(message, ' ') + 1;
      count[sender] += wordsCount;
      const int numWordsSent = count[sender];
      if (numWordsSent > maxWordsSent) {
        ans = sender;
        maxWordsSent = numWordsSent;
      } else if (numWordsSent == maxWordsSent && sender > ans) {
        ans = sender;
      }
    }

    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 largestWordCount(String[] messages, String[] senders) {
    final int n = messages.length;
    String ans = "";
    int maxWordsSent = 0;
    Map<String, Integer> count = new HashMap<>(); // {sender, the number of words sent}

    for (int i = 0; i < n; ++i) {
      final String message = messages[i];
      final String sender = senders[i];
      final int wordsCount = (int) message.chars().filter(c -> c == ' ').count() + 1;
      final int numWordsSent = count.merge(sender, wordsCount, Integer::sum);
      if (numWordsSent > maxWordsSent) {
        ans = sender;
        maxWordsSent = numWordsSent;
      } else if (numWordsSent == maxWordsSent && sender.compareTo(ans) > 0) {
        ans = sender;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def largestWordCount(self, messages: list[str], senders: list[str]) -> str:
    n = len(messages)
    ans = ''
    maxWordsSent = 0
    count = collections.Counter()  # [sender, # Words sent]

    for message, sender in zip(messages, senders):
      wordsCount = message.count(' ') + 1
      count[sender] += wordsCount
      numWordsSent = count[sender]
      if numWordsSent > maxWordsSent:
        ans = sender
        maxWordsSent = numWordsSent
      elif numWordsSent == maxWordsSent and sender > ans:
        ans = sender

    return ans