We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Number of Words Found in Sentences

Number: 2219

Difficulty: Easy

Paid? No

Companies: Apple, Google


Problem Description

You are given an array of strings sentences where each sentence consists of words separated by single spaces. The goal is to return the maximum number of words that appear in any single sentence.


Key Insights

  • Each sentence is well-formed with no leading or trailing spaces.
  • Words in a sentence are separated by a single space.
  • The problem can be solved by processing each sentence individually and counting the spaces (or splitting by space) to determine the word count.
  • The maximum word count across all sentences can be computed using a simple loop.

Space and Time Complexity

Time Complexity: O(n * m), where n is the number of sentences and m is the average length of each sentence. Space Complexity: O(m) for splitting each sentence into words.


Solution

We iterate over each sentence in the sentences list, split the sentence into words using the space character as the delimiter, calculate the number of words, and compare it with the current maximum. If it is greater, we update the maximum word count. This approach leverages basic string manipulation and looping constructs, ensuring an easy and efficient solution.


Code Solutions

# Function to find the maximum number of words in a list of sentences
def mostWordsFound(sentences):
    # Initialize maximum count to zero
    max_words = 0
    # Iterate over each sentence in the list
    for sentence in sentences:
        # Split the sentence by space to get list of words
        words = sentence.split(" ")
        # Update max_words if current sentence has more words
        max_words = max(max_words, len(words))
    return max_words

# Example usage:
sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
print(mostWordsFound(sentences))  # Output should be 6
← Back to All Questions