Problem · String

Format a Newspaper Page

Learn this problem
MediumCapital OneINTERNOA

Problem statement

You are given an array of paragraphs paragraphs, an array aligns, and an integer width.

  • paragraphs[i] is the ith paragraph, represented as an ordered array of words.
  • aligns[i] is either LEFT or RIGHT and specifies how paragraph i is aligned.
  • width is the exact number of characters in every formatted output line.

Format the paragraphs in order. Within each paragraph, preserve the word order and separate adjacent words with one space. Greedily place as many consecutive words as possible on each line without making its length exceed width. If the next word does not fit, start a new line with that word.

After packing a line, fill its remaining positions with spaces. For LEFT alignment, append the spaces after the words. For RIGHT alignment, prepend the spaces before the words.

Return all formatted lines in paragraph order as a string array. Each returned string must contain exactly width characters.

Function

formatNewspaperPage(paragraphs: String[][], aligns: String[], width: int) → String[]

Examples

Example 1

paragraphs = [["The","quick","brown","fox"],["jumps","over","it"]]aligns = ["LEFT","RIGHT"]width = 10return = ["The quick ","brown fox ","jumps over","        it"]

The first paragraph is left-aligned. The quick and brown fox each use 9 characters, so each receives one trailing space. The second paragraph is right-aligned. jumps over already uses all 10 characters, while it receives eight leading spaces.

Constraints

  • paragraphs.length = aligns.length.
  • Every value in aligns is either LEFT or RIGHT.
  • width is positive.
  • Every word has length at most width.

More Capital One problems

drafts saved locally
public String[] formatNewspaperPage(String[][] paragraphs, String[] aligns, int width) {
  // write your code here
}
paragraphs[["The","quick","brown","fox"],["jumps","over","it"]]
aligns["LEFT","RIGHT"]
width10
expected["The quick", "brown fox", "jumps over", "it"]
checking account