FastPrepMinimum Lines for Two Wrapped Text Columns

Minimum Lines for Two Wrapped Text Columns

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
Learn

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) → int

Examples

Example 1

left = "I have eaten"right = "I am"maxWidth = 10return = 2

The 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 = 2

One row pairs alpha with all three right words, and the second row contains beta.

Example 3

left = "longword"right = "x"maxWidth = 10return = -1

The 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 30 words and at most 500 characters.
  • 3 <= maxWidth <= 100.
  • Texts contain lowercase English words separated by one or more ASCII spaces.

More Google problems

See Google hiring insights
public int minTwoColumnLines(String left, String right, int maxWidth) {
    // Write your code here.
}
left"I have eaten"
right"I am"
maxWidth10
expected2
Checking account…