00:00

Problem Statement

Input/Output Examples

Visual Explanation

Because the comparison is a strict >, a later word of the same length never replaces an earlier one. That single character in the code is what makes the first word win a tie.

Approaches

Both approaches split the text into words. One keeps the longest in a loop; the other asks a stream for its maximum.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. Splitting reads every character once and stores the words, so both approaches use O(n) time and space.

Interview Tips and Recommended Approach

  • Ask about ties. First word, last word or all of them? Use > to keep the first and >= to keep the last.
  • Split on \\s+, not on a single space. Otherwise, double spaces produce empty strings in the word array.
  • Clarify punctuation. With whitespace as the only separator, "fun!" is a four-character word. Strip punctuation first if the interviewer wants letters only.
  • Test blank and one-word inputs to make sure the method never throws and never returns null.

Recommended Approach: split() and a Loop

Why: it is easy to follow, handles extra spaces and blank input, and makes the tie rule visible through the strict comparison. It also uses only basic language features.