Start learning free

LESSON 221 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Longest Word in Java: Tracking the Best So Far

Practice Read the full explanation

Given an ArrayList of strings words, return the longest word: the one with the most letters.

If several words share the longest length, return the first of them.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: "pancakes"
Explanation: "pancakes" has 8 letters, more than "I" (1) and "love" (4).

Example 2:

Input: words = ["apple", "kiwi", "mango"]
Output: "apple"
Explanation: "apple" and "mango" both have 5 letters, the most. "apple" comes first, so it is the answer.

Example 3:

Input: words = ["code"]
Output: "code"
Explanation: With only one word, it is the longest.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • On a tie, the answer is the first of the longest words.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in Java, explained

    Problem overview

    The method longestWord receives a List<String> and returns the word with the most letters. If several words share the longest length, it returns the first of them. For ["I", "love", "pancakes"] the answer is pancakes. For ["apple", "kiwi", "mango"], "apple" and "mango" both have 5 letters, and "apple" comes first, so it wins. A list with one word returns that word.

    Approach: keep a champion

    You don't need to sort the words or compute every length first. Start with the first word as the champion. Then look at each word and, whenever it is longer than the champion, replace the champion. After the last word, the champion is the longest one. The same pattern finds a maximum number, a smallest value or a best score.

    The ties are decided by one character in the comparison. Replacing the champion only when a word is strictly longer means that an equally long later word never takes over, so the first of the longest words stays.

    Step by step

    1. Start with the first word. String longest = words.get(0); is safe because the lesson guarantees at least one word. Before any comparison, it is the best word seen so far.
    2. Loop over the words with for (String word : words). Every word gets one chance to beat the champion. The first pass compares the first word with itself, which changes nothing.
    3. Compare lengths with >. word.length() > longest.length() is true only for a strictly longer word.
    4. Replace the champion inside the if: longest = word;.
    5. Return longest after the loop, when every word has been compared.

    The solution in Java

    class Solution {
        public String longestWord(List<String> words) {
            String longest = words.get(0);
            for (String word : words) {
                if (word.length() > longest.length()) {
                    longest = word;
                }
            }
            return longest;
        }
    }
    

    Details worth knowing:

    • List.get(0). Lists are read with get(index), not with square brackets. On an empty list, get(0) throws an IndexOutOfBoundsException, which is why the guarantee of at least one word matters.
    • The variable holds a reference. longest = word doesn't copy the characters; both names point to the same string, and strings can't be changed, so that is harmless.
    • Ties. With ["ab", "cd", "ef", "abc", "xyz"] the method returns abc: "xyz" has the same length, but it isn't strictly longer.

    Watching the champion change

    For ["apple", "kiwi", "mango", "fig", "banana"], this is the value of longest after each word has been looked at:

    apple -> apple
    kiwi -> apple
    mango -> apple
    fig -> apple
    banana -> banana
    

    "mango" ties "apple" at 5 letters and doesn't replace it. Only "banana", with 6, takes over. The champion changes at most once per word, and it never goes back to a shorter word, which is why one pass is enough.

    An empty list is outside the lesson's rules. Calling get(0) on one fails with Index 0 out of bounds for length 0. If you ever need to handle that case, check words.isEmpty() before the loop and decide what to return.

    Edge cases and common mistakes

    • Using >=. The last of the longest words would win instead of the first. For ["apple", "kiwi", "mango"] the answer would be mango.
    • Starting with an empty string. It works for non-empty words, but starting with words.get(0) is the habit that also works for numbers, where no neutral starting value exists.
    • Comparing the strings themselves. word > longest doesn't compile in Java. Compare lengths, not the words.
    • Returning the length. The method returns the word, not its number of letters.

    Testing

    • ["I", "love", "pancakes"] gives pancakes.
    • ["apple", "kiwi", "mango"] gives apple.
    • ["code"] gives code.
    • ["ab", "cd", "ef", "abc", "xyz"] gives abc.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free