How can you count the frequency of each word in a given string? This is a string
- User
How can you count the frequency of each word in a given string? This is a string
Assistant
How can you count the frequency of each word in a given string? This is a string
Problem Definition: Count occurrences of each unique word in a string
Key Considerations:
Approach Hierarchy:
Algorithm Analysis:
Implementation choices:
Input: A string containing text Output: A dictionary/map of each word to its occurrence count
| Consideration | Decision | Rationale |
|---|---|---|
| Word boundary | Whitespace + punctuation | Handles natural language |
| Case sensitivity | Case-insensitive | "The" and "the" are same word |
| Punctuation | Strip from words | "word," should count as "word" |
| Empty results | Return empty dict | Graceful handling |
import re
from collections import Counter
from typing import Dict
def count_word_frequency(text: str) -> Dict[str, int]:
"""
Count the frequency of each word in a string.
Args:
text: Input string to analyze
Returns:
Dictionary mapping each word to its count
"""
if not text or not text.strip():
return {}
# Convert to lowercase and extract words
# \w+ matches word characters (letters, digits, underscores)
# This automatically handles punctuation separation
words = re.findall(r'\b\w+\b', text.lower())
# Count occurrences using Counter
return dict(Counter(words))
# Alternative manual implementation (no Counter)
def count_word_frequency_manual(text: str) -> Dict[str, int]:
"""Manual implementation without using Counter."""
if not text or not text.strip():
return {}
words = re.findall(r'\b\w+\b', text.lower())
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
return frequency
# Test with provided example
if __name__ == "__main__":
test_string = "This is a string"
result = count_word_frequency(test_string)
print(f"Input: '{test_string}'")
print(f"Output: {result}")
Input: 'This is a string'
Output: {'this': 1, 'is': 1, 'a': 1, 'string': 1}
For massive datasets (e.g., counting words across Wikipedia), use MapReduce:
┌─────────────────────────────────────────────────────────────┐
│ MAPREDUCE ARCHITECTURE │
├─────────────────────────────────────────────────────────────┤
│ │
│ Input Data │
│ ┌───────┐ ┌───────┐ ┌───────┐ │
│ │Chunk 1│ │Chunk 2│ │Chunk N│ (Split across nodes) │
│ └───┬───┘ └───┬───┘ └───┬───┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌───────┐ ┌───────┐ ┌───────┐ │
│ │ MAP │ │ MAP │ │ MAP │ Emit: (word, 1) │
│ │(word,1)│ │(word,1)│ │(word,1)│ │
│ └───┬───┘ └───┬───┘ └───┬───┘ │
│ │ │ │ │
│ └────────┬┴─────────┘ │
│ ▼ │
│ ┌─────────────┐ │
│ │ SHUFFLE │ Group by key │
│ │ & SORT │ (word → [1,1,1,1...]) │
│ └──────┬──────┘ │
│ │ │
│ ┌────────┼────────┐ │
│ ▼ ▼ ▼ │
│ ┌───────┐ ┌───────┐ ┌───────┐ │
│ │REDUCE │ │REDUCE │ │REDUCE │ Sum all counts │
│ │ │ │ │ │ │ (word → total) │
│ └───┬───┘ └───┬───┘ └───┬───┘ │
│ └────────┬┴─────────┘ │
│ ▼ │
│ ┌─────────────┐ │
│ │Final Output │ {word: frequency} │
│ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
# MAP phase (runs on each chunk)
def mapper(text_chunk):
for word in extract_words(text_chunk):
emit(word, 1)
# REDUCE phase (aggregates counts)
def reducer(word, counts):
emit(word, sum(counts))
| Approach | Time | Space | Best For |
|---|---|---|---|
| Hash Map | O(n) | O(k) | Single strings, small files |
| Streaming | O(n) | O(k) | Large files, memory-constrained |
| MapReduce | O(n/p + log p) | O(k/p) per node | Distributed big data |
n = string length, k = unique words, p = number of partitions