Word Wrap with Even Justification
Updated
Problem statement
Format a sequence of words into fixed-width lines. A word is any run of non-whitespace characters, so it may contain letters, digits, punctuation and other symbols. Any run of whitespace separates words, except that whitespace immediately around a hyphen is ignored, so go - to becomes go-to.
Pack words greedily using one space while deciding what fits. Every returned line must then have exactly width characters. For a line with multiple words, distribute as many spaces as possible equally between every adjacent pair and append any remainder to the end. Center a one-word line, placing an unmatched extra space at the end.
Keep a hyphenated word intact when its normalized form fits within width. When it is longer than width, repeatedly split at the rightmost hyphen whose left piece, including that hyphen, fits; treat the pieces as consecutive words.
Function
justifyWords(text: String, width: int) → String[]Examples
Example 1
text = "a cat is an animal"width = 6return = ["a cat","is an","animal"]After greedy packing, final justification gives both two-word lines six characters.
Example 2
text = "cat is an animal and so is a dog"width = 12return = ["cat is an ","animal and","so is a dog "]The first line has two spaces per gap and one leftover space at the end.
Example 3
text = "auto-complete is my go - to"width = 8return = [" auto- ","complete","is my"," go-to "]The long hyphenated word splits after auto-, while whitespace around the hyphen in go - to is ignored.
Example 4
text = "Ship v2.0 now!"width = 9return = ["Ship v2.0"," now! "]Words may contain digits and punctuation. Ship v2.0 fills the first line exactly, and now! is centered with two spaces before it and three after.
Constraints
1 <= text.length <= 100000.1 <= width <= 200.- Whitespace in
textis a space, tab, newline or carriage return; every other character is a printable ASCII character such as a letter, digit, punctuation mark, symbol or hyphen. - After normalizing whitespace around hyphens, every ordinary word and every segment between allowed hyphen splits fits within
width.
More Sentry interview questions
Similar questions at other companies
- Greedy and Beam Sentence DecodingMicrosoft · PHONE SCREEN · ONSITE INTERVIEWMicrosoft interview questions
- Text JustificationUber · PHONE SCREENUber interview questions
- Max Number of OperationsSalesforce · OASalesforce interview questions
- Robot Assembly Line ConflictsGoogle · OAGoogle interview questions
- Minimum Steps on a Circular Letter DialIBM · OAIBM interview questions
- Format a Centered Newspaper PageVisa · OAVisa interview questions
- Choose the Next Hidden-Word GuessCharacter.AI · PHONE SCREEN
- Choose the Next Hidden-Word GuessFlexport · ONSITE INTERVIEWFlexport interview questions
- URL Segment Compression Part 3 — Global Token BudgetStripe · ONSITE INTERVIEWStripe interview questions
- Lexicographically Largest IdentifierAmazon · OA