#192

Word Frequency

Medium
ShellHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages a single pass through the file to count word frequencies using a hash map, followed by sorting the results. This significantly reduces the time complexity compared to the brute-force approach.

⚙️

Algorithm

5 steps
  1. 1Step 1: Read the contents of the file and split it into words.
  2. 2Step 2: Use a hash map to count the occurrences of each word in a single pass.
  3. 3Step 3: Convert the hash map to a list of tuples for sorting.
  4. 4Step 4: Sort the list based on frequency in descending order.
  5. 5Step 5: Print the sorted list.
solution.py7 lines
1from collections import Counter
2
3with open('words.txt') as f:
4    words = f.read().split()
5    counts = Counter(words)
6    for word, freq in counts.most_common():
7        print(word, freq)

Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the word counts in a hash map.

  • 1Using a hash map allows for efficient counting of word frequencies.
  • 2Sorting the results is necessary for presenting the output in the required order.

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