FastPrepReflow and Fully Justify Text Lines

Reflow and Fully Justify Text Lines

Intuit logoIntuit● MediumNEW GRADINTERNOA

Problem statement

You receive an array of existing text lines and a target maxWidth. Read the words from all input lines in their original order, treating each old line break as a word boundary. Reflow them into new lines.

For this exercise, assume greedy packing: put as many next words on each new line as fit when adjacent words need at least one space. Never split or reorder a word.

Every new line containing two or more words must have exactly maxWidth characters, including the final line. Distribute spaces between its words as evenly as possible. For this exercise, assume any extra spaces go to the leftmost gaps first.

A line containing only one word is returned as that word with no padding. Use actual ASCII spaces between words; hyphens in an original example are only stand-ins that make spaces visible. Return an empty array when the input line array is empty.

Function

reflowJustify(lines: String[], maxWidth: int) → String[]

Examples

Example 1

lines = ["It was the best","of times it was","the worst of times"]maxWidth = 12return = ["It  was  the","best      of","times it was","the worst of","times"]

The original twelve words form five lines. The first four lines have length 12, with spaces only between words. The final line contains only times, so it remains length 5 without padding.

Example 2

lines = ["a bb c","dddd"]maxWidth = 9return = ["a   bb  c","dddd"]

The first line has four letter characters and five spaces. Its two gaps receive three and two spaces, in that order. The final single word dddd is returned without padding.

Constraints

  • For this exercise, assume 0 <= lines.length <= 20 and each supplied line has 1 to 200 characters.
  • 1 <= maxWidth <= 100.
  • Each supplied line consists of ASCII letter words separated by one space, with no leading or trailing spaces. A word contains only A through Z or a through z.
  • No word is longer than maxWidth. An input line may be longer than maxWidth.

More Intuit problems

See Intuit hiring insights
Saved
public String[] reflowJustify(String[] lines, int maxWidth) {
    // Write your code here
}
lines["It was the best","of times it was","the worst of times"]
maxWidth12
expected["It was the", "best of", "times it was", "the worst of", "times"]
Checking account…