FastPrepCrop Text at a Whole-Word Boundary
Problems/Crop Text at a Whole-Word Boundary

Crop Text at a Whole-Word Boundary

American Express logoAmerican Express● EasyFULLTIMEOA

Updated Aug 2026

QuestionFunctionExamplesConstraints

Problem statement

Source note: The original report specifies truncating text without splitting a word or leaving a trailing space. It does not define whitespace normalization, input bounds, or the empty-result case. This practice version uses single-space-separated words and returns an empty string when the first word does not fit.

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 interview questions

  • Maximum Points in a Perimeter-Bounded RectangleOA · Seen Sep 2026
  • Minimum Moves to Spread Stones Across a GridOA · Seen Sep 2026
  • Largest Two Non-Overlapping Buildable SquaresOA · Seen Aug 2026
  • Maximum Sum of Two Sign-Flipping WindowsOA · Seen Aug 2026
  • Minimum Parking Roof LengthOA · Seen Aug 2026
  • Minimum Pile Reduction StepsOA · Seen Aug 2026
  • Disjoint Target-Sum TripletsPHONE SCREEN · Seen Mar 2025

Similar questions at other companies

  • Maximum Ones After K OperationsGoldman Sachs · OA
  • Minimum Operations to Reduce a Transaction LedgerVisa · OA
  • Prepare NotificationMicrosoft · OA
  • Minimum Changes for Distinct Adjacent CharactersHeadlands Technologies · OA
  • Largest Number With Even Digit FrequenciesDRW · OA
  • Minimum Replacements for Unequal Adjacent CharactersIBM · OA
  • Minimum Flips for Even Binary RunsJP Morgan Chase · OA
  • Missing WordsVanguard · OA
  • Digit Changes for a Multiple of 9Nutanix · OA
  • Smallest String After at Most One DeletionLSEG · OA
See American Express hiring insights
Saved
class Solution {
    public String cropWords(String text, int maxCharacters) {
        // Write your code here.
    }
}
Checking account…