Code Logo

Longest Word Length

Published at25 Jul 2026
Medium 0 views
Like0

Given a string of words separated by single spaces, find the length of the longest word. Return the maximum word length as an integer.

For example, in "The quick brown fox jumps", the longest word is "jumps" with length 5. In "Hello world", the longest is "Hello" with length 5. In "a bb ccc", the longest is "ccc" with length 3. An empty string returns 0.

Finding the longest word is a common text processing task used in readability analysis, typography (setting appropriate container widths), and natural language processing. The solution splits the string into words and tracks the maximum length encountered.

The algorithm splits the string by spaces into an array of words, iterates through each word, compares its length to the current maximum, and updates if longer. After processing all words, return the maximum length found.

Edge cases include an empty string (return 0), a single-word string (return its length), multiple words with the same length (return that length), and strings with leading/trailing spaces (the split handles them correctly when using space delimiter).

Example Input & Output

Example 1
Input
"a bc def"
Output
3
Explanation

Longest word 'def' has 3

Example 2
Input
"a bb ccc dddd eeeee"
Output
5
Explanation

'eeeee' has 5 letters

Example 3
Input
"one"
Output
3
Explanation

Single word

Example 4
Input
"The quick brown fox"
Output
5
Explanation

Longest word 'quick' has 5 letters

Example 5
Input
""
Output
0
Explanation

Empty string

Algorithm Flow

Recommendation Algorithm Flow for Longest Word Length
Recommendation Algorithm Flow for Longest Word Length

Solution Approach

Split the string into words and track the maximum word length.

function longestWordLength(s)
  if s is empty then return 0
  words = split(s, " ")
  maxLen = 0
  for each w in words
    if length(w) > maxLen then maxLen = length(w)
  return maxLen

Handle the empty string case. Split the input on spaces to get an array of words. Initialize maxLen to 0. Iterate through each word; if its character count exceeds maxLen, update maxLen. Return maxLen after the loop.

Time complexity is O(n) where n is the string length. Space complexity is O(n) for the words array.

Best Answers

java
class Solution {
    public int solution(String s) {
        if(s.isEmpty())return 0;
        String[] w=s.split(" ");int m=0;
        for(int i=0;i<w.length;i++){if(w[i].length()>m)m=w[i].length();}
        return m;
    }
}