00:00

Problem Statement

Input/Output Examples

Visual Explanation

The loop keeps one flag, startOfWord, which is true at the beginning and after every whitespace character. The first non-space character after that is uppercased, and the flag turns off until the next space.

Approaches

The loop works character by character. The split approach works word by word and joins the words back together.

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. Both approaches visit each character a constant number of times and build a new string of length n.

Interview Tips and Recommended Approach

  • Clarify the rest of the word. Should "jAVA" become "JAVA" or "Java"? This page keeps the other letters as they are.
  • Watch for empty pieces. word.charAt(0) on an empty string throws StringIndexOutOfBoundsException, which happens with double spaces.
  • Explain split(" ", -1). Without the limit, trailing empty strings are removed and trailing spaces are lost.
  • Test unusual input: leading spaces, several spaces in a row, digits at the start of a word and an empty string.

Recommended Approach: StringBuilder Loop

Why: it reads the string once, preserves every whitespace character exactly and has no empty-string pitfalls. The flag-based loop is also a reusable pattern for other word-boundary problems.