FastPrepReflow Text with Balanced Hyphens

Reflow Text with Balanced Hyphens

Atlassian logoAtlassian● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Flatten the words from the strings in text, preserving their order, and reflow them into lines of maximum width width. Never split a word. Select the largest consecutive group of words that fits when separated by one hyphen.

Distribute hyphens between words as evenly as possible to reach the width on each fully justified line. Gap lengths may differ by at most one; put any extra separator characters in the leftmost gaps.

Leave the final line unpadded with one hyphen between its words. For this exercise, assume every singleton line is also left unpadded, including a nonfinal singleton.

For this exercise, assume input contains only English letters and ASCII spaces. Ignore leading, trailing and repeated spaces inside source strings; source-string boundaries act as whitespace. An empty input or input without words returns an empty array.

Function

justifyHyphenText(text: String[], width: int) → String[]

Examples

Example 1

text = ["The day began as still as the","night abruptly lighted with","brilliant flame"]width = 24return = ["The--day--began-as-still","as--the--night--abruptly","lighted--with--brilliant","flame"]

The complete original width 24 fixture is preserved; all three justified strings are exactly 24 characters and flame is unchanged.

Example 2

text = ["a bb ccc d e f"]width = 6return = ["a---bb","ccc--d","e-f"]

This authored fixture leaves the final multiword line e-f unpadded.

Example 3

text = ["abcdefg a b"]width = 8return = ["abcdefg","a-b"]

This authored fixture demonstrates the declared unpadded nonfinal singleton interpretation.

Constraints

  • For this exercise, assume 0 <= text.length <= 100 and the total number of input characters is at most 2000.
  • For this exercise, assume 1 <= width <= 100, and every nonempty word has length at most width.
  • Each input string contains only uppercase or lowercase English letters and ASCII spaces.

More Atlassian problems

See Atlassian hiring insights
public String[] justifyHyphenText(String[] text, int width) {
    // Write your code here.
    return new String[0];
}
text["The day began as still as the","night abruptly lighted with","brilliant flame"]
width24
expected["The--day--began-as-still", "as--the--night--abruptly", "lighted--with--brilliant", "flame"]
Checking account…