Minimum Lines for Two Wrapped Text Columns
Problem statement
Two space-separated texts must be printed side by side within a page of width maxWidth. The two text fragments on a row are separated by the three-character delimiter | .
On each row, take a consecutive, nonempty group of remaining words from the left text, the right text, or both. Preserve every word and its order, use one space between adjacent words from the same text, and require the two fragment lengths plus three to be at most maxWidth. The separator position may differ between rows.
Return the minimum number of rows needed to consume both texts. Return -1 when some word cannot fit even on a row by itself. Two empty texts use zero rows.
Function
minTwoColumnLines(left: String, right: String, maxWidth: int) → intExamples
Example 1
left = "I have eaten"right = "I am"maxWidth = 10return = 2The two rows are I have | I and eaten | am; their separator positions may differ.
Example 2
left = "alpha beta"right = "x y z"maxWidth = 15return = 2One row pairs alpha with all three right words, and the second row contains beta.
Example 3
left = "longword"right = "x"maxWidth = 10return = -1The left word needs eight characters plus the three-character separator, exceeding the page width even when the right fragment is empty.
Constraints
- Each text contains at most
30words and at most500characters. 3 <= maxWidth <= 100.- Texts contain lowercase English words separated by one or more ASCII spaces.