#2284

Sender With Largest Word Count

Medium
ArrayHash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass through the messages and senders to count the words for each sender using a hash map. This approach is efficient because it minimizes the number of iterations and leverages direct access to counts.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a hash map to store the total word counts for each sender.
  2. 2Step 2: Iterate through the messages and senders simultaneously.
  3. 3Step 3: For each message, calculate the word count and update the corresponding sender's count in the hash map.
  4. 4Step 4: After processing all messages, iterate through the hash map to find the sender with the maximum word count.
  5. 5Step 5: Handle ties by comparing sender names lexicographically.
solution.py14 lines
1# Full working Python code
2messages = ["Hello userTwooo", "Hi userThree", "Wonderful day Alice", "Nice day userThree"]
3senders = ["Alice", "userTwo", "userThree", "Alice"]
4
5def largest_sender(messages, senders):
6    word_count = {}
7    for i in range(len(messages)):
8        count = len(messages[i].split())
9        sender = senders[i]
10        word_count[sender] = word_count.get(sender, 0) + count
11    max_sender = max(word_count.keys(), key=lambda x: (word_count[x], x))
12    return max_sender
13
14print(largest_sender(messages, senders))

Complexity note: The time complexity is O(n) because we only make a single pass through the messages and senders. The space complexity is O(n) due to the hash map storing the word counts for each sender.

  • 1Using a hash map allows for efficient counting and retrieval of word counts.
  • 2Lexicographical comparison is crucial when handling ties.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.