Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2284. Sender With Largest Word Count

Explanation

To solve this problem, we can iterate through the messages and keep track of the word count for each sender using a HashMap. After calculating the word count for each sender, we can then find the sender with the largest word count. In case of a tie, we return the sender with the lexicographically largest name.

  • Create a HashMap to store the word count for each sender.
  • Iterate through the messages array and split each message into words.
  • Update the word count for the sender of the current message.
  • Find the sender with the largest word count. If there is a tie, return the sender with the lexicographically largest name.
import java.util.*;

class Solution {
    public String largestSender(String[] messages, String[] senders) {
        Map<String, Integer> wordCount = new HashMap<>();
        
        for (int i = 0; i < messages.length; i++) {
            String sender = senders[i];
            String[] words = messages[i].split(" ");
            wordCount.put(sender, wordCount.getOrDefault(sender, 0) + words.length);
        }
        
        String largestSender = "";
        int maxCount = 0;
        
        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
            if (entry.getValue() > maxCount || (entry.getValue() == maxCount && entry.getKey().compareTo(largestSender) > 0)) {
                maxCount = entry.getValue();
                largestSender = entry.getKey();
            }
        }
        
        return largestSender;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.