Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i].
A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message.
Return the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name.
Note:
"Alice" and "alice" are distinct.Example 1:
Input: messages = ["Hello userTwooo","Hi userThree","Wonderful day Alice","Nice day userThree"], senders = ["Alice","userTwo","userThree","Alice"] Output: "Alice" Explanation: Alice sends a total of 2 + 3 = 5 words. userTwo sends a total of 2 words. userThree sends a total of 3 words. Since Alice has the largest word count, we return "Alice".
Example 2:
Input: messages = ["How is leetcode for everyone","Leetcode is useful for practice"], senders = ["Bob","Charlie"] Output: "Charlie" Explanation: Bob sends a total of 5 words. Charlie sends a total of 5 words. Since there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.
Constraints:
n == messages.length == senders.length1 <= n <= 1041 <= messages[i].length <= 1001 <= senders[i].length <= 10messages[i] consists of uppercase and lowercase English letters and ' '.messages[i] are separated by a single space.messages[i] does not have leading or trailing spaces.senders[i] consists of uppercase and lowercase English letters only.Problem summary: You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i]. A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message. Return the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name. Note: Uppercase letters come before lowercase letters in lexicographical order. "Alice" and "alice" are distinct.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
["Hello userTwooo","Hi userThree","Wonderful day Alice","Nice day userThree"] ["Alice","userTwo","userThree","Alice"]
["How is leetcode for everyone","Leetcode is useful for practice"] ["Bob","Charlie"]
top-k-frequent-elements)top-k-frequent-words)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2284: Sender With Largest Word Count
class Solution {
public String largestWordCount(String[] messages, String[] senders) {
Map<String, Integer> cnt = new HashMap<>(senders.length);
for (int i = 0; i < messages.length; ++i) {
int v = 1;
for (int j = 0; j < messages[i].length(); ++j) {
if (messages[i].charAt(j) == ' ') {
++v;
}
}
cnt.merge(senders[i], v, Integer::sum);
}
String ans = senders[0];
for (var e : cnt.entrySet()) {
String k = e.getKey();
int v = e.getValue();
if (cnt.get(ans) < v || (cnt.get(ans) == v && ans.compareTo(k) < 0)) {
ans = k;
}
}
return ans;
}
}
// Accepted solution for LeetCode #2284: Sender With Largest Word Count
func largestWordCount(messages []string, senders []string) string {
cnt := make(map[string]int)
for i, message := range messages {
v := strings.Count(message, " ") + 1
cnt[senders[i]] += v
}
ans := senders[0]
for k, v := range cnt {
if cnt[ans] < v || (cnt[ans] == v && ans < k) {
ans = k
}
}
return ans
}
# Accepted solution for LeetCode #2284: Sender With Largest Word Count
class Solution:
def largestWordCount(self, messages: List[str], senders: List[str]) -> str:
cnt = Counter()
for message, sender in zip(messages, senders):
cnt[sender] += message.count(" ") + 1
ans = senders[0]
for k, v in cnt.items():
if cnt[ans] < v or (cnt[ans] == v and ans < k):
ans = k
return ans
// Accepted solution for LeetCode #2284: Sender With Largest Word Count
/**
* [2284] Sender With Largest Word Count
*
* You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i].
* A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message.
* Return the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name.
* Note:
*
* Uppercase letters come before lowercase letters in lexicographical order.
* "Alice" and "alice" are distinct.
*
*
* Example 1:
*
* Input: messages = ["Hello userTwooo","Hi userThree","Wonderful day Alice","Nice day userThree"], senders = ["Alice","userTwo","userThree","Alice"]
* Output: "Alice"
* Explanation: Alice sends a total of 2 + 3 = 5 words.
* userTwo sends a total of 2 words.
* userThree sends a total of 3 words.
* Since Alice has the largest word count, we return "Alice".
*
* Example 2:
*
* Input: messages = ["How is leetcode for everyone","Leetcode is useful for practice"], senders = ["Bob","Charlie"]
* Output: "Charlie"
* Explanation: Bob sends a total of 5 words.
* Charlie sends a total of 5 words.
* Since there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.
*
* Constraints:
*
* n == messages.length == senders.length
* 1 <= n <= 10^4
* 1 <= messages[i].length <= 100
* 1 <= senders[i].length <= 10
* messages[i] consists of uppercase and lowercase English letters and ' '.
* All the words in messages[i] are separated by a single space.
* messages[i] does not have leading or trailing spaces.
* senders[i] consists of uppercase and lowercase English letters only.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/sender-with-largest-word-count/
// discuss: https://leetcode.com/problems/sender-with-largest-word-count/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/sender-with-largest-word-count/solutions/5300813/two-line-solution-beats-88-at-speed-hash-gr14/
pub fn largest_word_count(messages: Vec<String>, senders: Vec<String>) -> String {
let generate_map = || {
let mut map = std::collections::HashMap::new();
map.insert(String::new(), 0);
map
};
senders
.into_iter()
.zip(messages.into_iter())
.fold(
(String::new(), generate_map()),
|(max_sender, mut map), (sender, message)| {
*map.entry(sender.clone()).or_insert(0) += message.split(" ").count() as i32;
let (cmp1, cmp2) = (
map[&sender] > map[&max_sender],
map[&sender] == map[&max_sender],
);
if cmp1 || cmp2 && sender > max_sender {
(sender, map)
} else {
(max_sender, map)
}
},
)
.0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2284_example_1() {
let messages = vec_string![
"Hello userTwooo",
"Hi userThree",
"Wonderful day Alice",
"Nice day userThree"
];
let senders = vec_string!["Alice", "userTwo", "userThree", "Alice"];
let result = "Alice".to_string();
assert_eq!(Solution::largest_word_count(messages, senders), result);
}
#[test]
fn test_2284_example_2() {
let messages = vec_string![
"How is leetcode for everyone",
"Leetcode is useful for practice"
];
let senders = vec_string!["Bob", "Charlie"];
let result = "Charlie".to_string();
assert_eq!(Solution::largest_word_count(messages, senders), result);
}
}
// Accepted solution for LeetCode #2284: Sender With Largest Word Count
function largestWordCount(messages: string[], senders: string[]): string {
const cnt: { [key: string]: number } = {};
for (let i = 0; i < messages.length; ++i) {
const v = messages[i].split(' ').length;
cnt[senders[i]] = (cnt[senders[i]] || 0) + v;
}
let ans = senders[0];
for (const k in cnt) {
if (cnt[ans] < cnt[k] || (cnt[ans] === cnt[k] && ans < k)) {
ans = k;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.