Crop Text at a Whole-Word Boundary
Updated
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) → StringExamples
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 <= 2000000 <= maxCharacters <= 1000000textcontains 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