Problem · String

Crop Text at a Whole-Word Boundary

Learn this problem
EasyAmerican Express logoAmerican ExpressFULLTIMEOA

Problem statement

You are given a nonempty string text containing nonempty words separated by single spaces, and a nonnegative integer maxCharacters.

Return the longest prefix of text that:

  • has length at most maxCharacters,
  • contains only complete words from the beginning of text, and
  • does not end with a space.

If the first word does not fit, return the empty string.

Function

cropWords(text: String, maxCharacters: int) → String

Examples

Example 1

text = "The quick brown fox"maxCharacters = 10return = "The quick"

Adding the next word would make the prefix longer than 10 characters, so the result ends after quick.

Example 2

text = "hello world"maxCharacters = 4return = ""

The first word has five characters, so no complete word fits.

Example 3

text = "one two"maxCharacters = 7return = "one two"

The entire text has exactly seven characters.

Constraints

  • 1 <= text.length <= 200000
  • 0 <= maxCharacters <= 1000000
  • text contains printable non-space characters grouped into words separated by exactly one space.

More American Express problems

drafts saved locally
public String cropWords(String text, int maxCharacters) {
    // Write your code here.
}
text"The quick brown fox"
maxCharacters10
expected"The quick"
checking account