#2114

Maximum Number of Words Found in Sentences

Easy
ArrayStringString ManipulationArray Traversal
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution leverages a single pass through the sentences to count words, which is more efficient than repeatedly splitting strings. This reduces unnecessary computations and improves performance.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to keep track of the maximum word count.
  2. 2Step 2: Loop through each sentence in the sentences array.
  3. 3Step 3: Count the number of spaces in the sentence, which gives the number of words as spaces + 1.
  4. 4Step 4: Update the maximum word count if the current count is greater than the maximum.
solution.py8 lines
1# Full working Python code
2
3def maxWords(sentences):
4    max_count = 0
5    for sentence in sentences:
6        word_count = sentence.count(' ') + 1
7        max_count = max(max_count, word_count)
8    return max_count

Complexity note: The time complexity is O(n) because we are processing each sentence once, and the space complexity is O(1) since we only use a few variables.

  • 1Counting spaces gives a direct way to determine the number of words.
  • 2Using string manipulation functions can simplify the counting process.

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