Talentd
FleetCode
Make and follow sheets.Sign in

Maximum Number of Words Found in Sentences solution and explanation

EasyArrayString5 min read86.6% acceptanceUpdated 9 Apr 2026
2114. Maximum Number of Words Found in Sentences (Leetcode Easy)Programming Live with Larry · 3:34 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. 2114. Maximum Number of Words Found in Sentences (Leetcode Easy)Programming Live with Larry · 3:34 · 2K views
  2. LEETCODE SOLUTION 2114 | Maximum Number of Words Found | Leetcode for BEGINNERS | EASY | JavascriptCodingForBeginners · 8:45 · 2K views
  3. Leetcode | 2114. Maximum Number of Words Found in Sentences | Easy | Java SolutionDeveloper Docs · 4:54 · 1K views
  4. 2114. Maximum Number of Words Found in Sentences || leetcodeFang Coder · 3:26 · 934 views
  5. Maximum Number of Words Found in Sentences| LeetCode 2114 | CppCodeClips with Abhishek Ranjan · 5:53 · 837 views
  6. Leet Code in Python | Maximum Number of Words Found in Sentences | DSA | Competitive Day 9Surendar Manoj · 14:36 · 277 views
  7. LeetCode 2114 | Maximum Number of Words Found in Sentences 🔥 | Easy C++ SolutionManan patel · 7:52 · 220 views
  8. LeetCode 2114. Maximum Number of Words Found in SentencesYusuke · 1:58 · 164 views
  9. Leetcode | 2114. Maximum Number of Words Found in Sentencesapril mix · 0:58 · 151 views
  10. Crack LeetCode Q.2114: Maximum Number of Words Found in Sentences (Java Solution!)CodoPhilic · 6:11 · 137 views

The problem

A sentence is a list of words that are separated by a single space with no leading or trailing spaces.

You are given an array of strings sentences, where each sentences[i] represents a single sentence.

Return the maximum number of words that appear in a single sentence.

Example 1:

Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
Output: 6
Explanation: 
- The first sentence, "alice and bob love leetcode", has 5 words in total.
- The second sentence, "i think so too", has 4 words in total.
- The third sentence, "this is great thanks very much", has 6 words in total.
Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.

Example 2:

Input: sentences = ["please wait", "continue to fight", "continue to win"]
Output: 3
Explanation: It is possible that multiple sentences contain the same number of words. 
In this example, the second and third sentences (underlined) have the same number of words.

Constraints:

  • 1 <= sentences.length <= 100
  • 1 <= sentences[i].length <= 100
  • sentences[i] consists only of lowercase English letters and ' ' only.
  • sentences[i] does not have leading or trailing spaces.
  • All the words in sentences[i] are separated by a single space.

Approach overview

Problem Overview: You receive an array of sentences where each sentence contains words separated by single spaces. The task is simple: determine the maximum number of words that appear in any single sentence.

The key observation is that the number of words in a sentence equals the number of spaces plus one. Every space separates two words, so counting spaces becomes the fastest way to compute the word count. Since each sentence is processed independently, the goal is to scan each string and track the maximum word count seen so far.

Approach 1: Counting Spaces Method (Time: O(n), Space: O(1))

This approach relies on the observation that words are separated by exactly one space. Iterate through each sentence in the array and count how many spaces it contains using a simple loop or built‑in string operation. The number of words equals spaces + 1. Maintain a variable that stores the maximum word count encountered while iterating through the list of sentences.

The algorithm scans every character once across all sentences, so the total time complexity is O(n), where n is the total number of characters across the input array. Space complexity remains O(1) because only a few integer counters are used. This is the most direct solution and works well for problems involving simple string processing inside an array.

Approach 2: Iterative Character Count Method (Time: O(n), Space: O(1))

This method performs a full character scan for each sentence while explicitly counting words. Start with a word counter initialized to 1 for every non-empty sentence, then iterate through each character. Every time you encounter a space character (' '), increment the word counter. After processing the sentence, compare the result with the global maximum and update it if necessary.

The complexity remains O(n) because each character is visited exactly once. Space usage stays O(1). While this approach produces the same result as the previous one, it makes the counting logic explicit and is sometimes easier to adapt if the delimiter rules change (for example, handling multiple spaces or different separators).

Recommended for interviews: The Counting Spaces Method is the expected solution. Interviewers want to see that you recognize the relationship between spaces and word counts instead of splitting strings or allocating extra arrays. A brute approach using split() also works but increases memory usage to O(w) where w is the number of words. Demonstrating the space-count insight shows strong attention to problem constraints and efficient string traversal.

Approach 1: Counting Spaces Method

This approach involves counting the number of spaces in each sentence. The number of words in a sentence will be the number of spaces plus one since words are separated by a single space.

def mostWordsFound(sentences):
    return max(len(sentence.split()) for sentence in sentences)
import java.util.*;

public class Solution {
    public int mostWordsFound(String[] sentences) {
        int maxWords = 0;
        for (String sentence : sentences) {
            int wordCount = sentence.split(" ").length;
            maxWords = Math.max(maxWords, wordCount);
        }
        return maxWords;
    }
}
#include <iostream>
#include <vector>
#include <string>

int mostWordsFound(std::vector<std::string>& sentences) {
    int maxWords = 0;
    for (const auto& sentence : sentences) {
        int wordCount = 1 + std::count(sentence.begin(), sentence.end(), ' ');
        maxWords = std::max(maxWords, wordCount);
    }
    return maxWords;
}
function mostWordsFound(sentences) {
    return Math.max(...sentences.map(sentence => sentence.split(' ').length));
}
#include <stdio.h>
#include <string.h>
#define MAX_SENTENCES 100

int mostWordsFound(char sentences[][100], int sentencesSize) {
    int maxWords = 0;
    for (int i = 0; i < sentencesSize; i++) {
        int wordCount = 1;
        for (int j = 0; j < strlen(sentences[i]); j++) {
            if (sentences[i][j] == ' ') wordCount++;
        }
        if (wordCount > maxWords) maxWords = wordCount;
    }
    return maxWords;
}
using System;
using System.Linq;

public class Solution {
    public int MostWordsFound(string[] sentences) {
        return sentences.Max(sentence => sentence.Split(' ').Length);
    }
}

In this Python solution, we use list comprehension to split each sentence into words using the 'split()' method, which splits a string by its spaces. Then, we use Python's built-in 'max()' function to find the maximum length of the lists generated.

Complexity

Time Complexity: O(n * m), where n is the number of sentences and m is the longest sentence length in terms of words.
Space Complexity: O(1) additional space apart from input data.

Try this approach in the editor

Approach 2: Iterative Character Count Method

This method iteratively goes through each character of each sentence. It counts words by detecting spaces and updating the word count accordingly. This approach bypasses the need to use in-built functions like split.

def mostWordsFound(sentences):
    max_words = 0
    for sentence in sentences:
        count = 1
        for char in sentence:
            if char == ' ':
                count += 1
        max_words = max(max_words, count)
    return max_words
function mostWordsFound(sentences) {
    let maxWords = 0;
    for (let sentence of sentences) {
        let count = 1;
        for (let char of sentence) {
            if (char === ' ') count++;
        }
        maxWords = Math.max(maxWords, count);
    }
    return maxWords;
}

This solution iterates through each sentence and subsequently each character. Every time a space is encountered, it increases the word count. It keeps track of the maximum word count found.

Complexity

Time Complexity: O(n * m), where n is the number of sentences and m is the length of the longest sentence.
Space Complexity: O(1) since no additional space is allocated.

Try this approach in the editor

Approach 3: Space Counting

We iterate through the array sentences. For each sentence, we count the number of spaces, then the number of words is the number of spaces plus 1. Finally, we return the maximum number of words.

The time complexity is O(L), where L is the total length of all strings in the array sentences. The space complexity is O(1).

function mostWordsFound(sentences: string[]): number {
    return sentences.reduce(
        (r, s) =>
            Math.max(
                r,
                [...s].reduce((r, c) => r + (c === ' ' ? 1 : 0), 1),
            ),
        0,
    );
}
func mostWordsFound(sentences []string) (ans int) {
	for _, s := range sentences {
		cnt := 1 + strings.Count(s, " ")
		if ans < cnt {
			ans = cnt
		}
	}
	return
}
impl Solution {
    pub fn most_words_found(sentences: Vec<String>) -> i32 {
        let mut ans = 0;
        for s in sentences.iter() {
            let mut count = 1;
            for c in s.as_bytes() {
                if *c == b' ' {
                    count += 1;
                }
            }
            ans = ans.max(count);
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Counting Spaces Method

Time Complexity: O(n * m), where n is the number of sentences and m is the longest sentence length in terms of words.
Space Complexity: O(1) additional space apart from input data.

Iterative Character Count Method

Time Complexity: O(n * m), where n is the number of sentences and m is the length of the longest sentence.
Space Complexity: O(1) since no additional space is allocated.

Space Counting–

Complexity analysis

ApproachTimeSpaceWhen to Use
Counting Spaces MethodO(n)O(1)Best general solution when sentences use single spaces between words
Iterative Character CountO(n)O(1)Useful when implementing explicit character-level parsing or adapting to custom delimiters

Frequently asked questions

Is Maximum Number of Words Found in Sentences easy or hard?

Maximum Number of Words Found in Sentences is categorized as an Easy problem. The challenge mainly tests basic string manipulation and simple iteration over an array, making it suitable for beginners practicing fundamental coding interview patterns.

Maximum Number of Words Found in Sentences Python/Java solution

In Python, you can iterate through each sentence and count spaces using a loop or the count(' ') method, then add one to compute the number of words. In Java, iterate through characters in the string and increment a counter whenever a space appears. Both implementations run in O(n) time with O(1) extra space.

How to solve Maximum Number of Words Found in Sentences in O(n)?

Iterate through every sentence and count how many spaces it contains. Since each space separates two words, the number of words equals spaces plus one. Track the maximum word count while scanning the sentences, resulting in O(n) time and O(1) space.

What is the best approach for Maximum Number of Words Found in Sentences?

The most efficient approach counts spaces in each sentence and adds one to get the word count. Because words are separated by single spaces, this avoids creating extra arrays with split operations. The algorithm scans each character once, giving O(n) time complexity and O(1) space complexity.

Is Maximum Number of Words Found in Sentences asked at Google/Amazon/Meta?

This problem represents a typical easy-level string processing task commonly used in coding screens or early interview rounds. Variants that involve string parsing, counting delimiters, or processing arrays of sentences appear in interviews at companies like Amazon and Google to test basic problem-solving and attention to detail.

What data structure is used in Maximum Number of Words Found in Sentences?

The input is an array of strings, and the solution primarily relies on string traversal. No complex data structures are required—just simple counters while iterating through characters in each sentence.

What is the time complexity of Maximum Number of Words Found in Sentences?

The optimal time complexity is O(n), where n is the total number of characters across all sentences. Each sentence is scanned once to count spaces or detect word boundaries. Only constant extra memory is required, so the space complexity is O(1).

Comments

Now write it yourselfClose this page and solve Maximum Number of Words Found in Sentences in the editor, without looking.
Practise Maximum Number of Words Found in Sentences