Back to Pika questions
CodingSoftware Engineer

Right Alignment

Frequency: Reported


Given a paragraph as an array words, format it into right-aligned lines of exactly maxWidth characters.

  • Pack as many words as possible onto each line.
  • Separate words on the same line with one space.
  • Add any remaining spaces at the beginning of the line.
  • If a word is longer than maxWidth, begin it on a new line and emit consecutive chunks of maxWidth characters until its remaining suffix fits normally.

Punctuation is already included in each word.

Function

text
rightAlign(int maxWidth, string words[]) -> string[]

Constraints

text
1 <= maxWidth <= 10^5
the total length of all strings in words is <= 10^5
each word contains ASCII characters 33 through 126, excluding space

Submitted implementation

python
def rightAlign(maxWidth, words):
    res = []
    line = []
    length = 0

    for word in words:
        while len(word) > maxWidth:
            if line:
                s = ' '.join(line)
                res.append(' ' * (maxWidth - len(s)) + s)
                line = []
                length = 0
            chunk = word[:maxWidth]
            res.append(chunk)
            word = word[maxWidth:]

        if length + len(word) + (len(line) if line else 0) > maxWidth:
            s = ' '.join(line)
            res.append(' ' * (maxWidth - len(s)) + s)
            line = []
            length = 0

        line.append(word)
        length += len(word)

    if line:
        s = ' '.join(line)
        res.append(' ' * (maxWidth - len(s)) + s)

    return res

The source did not include worked examples.