09 Sept 2026Go / Python / TypeScriptEasy

Number of Lines To Write String

Compute the number of bounded-width lines needed for a string and the final line's width.

Accumulate character widths, starting a new line whenever the next character would exceed one hundred units.

complexity

O(n) time and O(1) extra space.

solution files

  • Go number-of-lines-to-write-string/solution.go
  • Python number-of-lines-to-write-string/solution.py
  • TypeScript number-of-lines-to-write-string/solution.ts

Solution files

Gonumber-of-lines-to-write-string/solution.go
package main

func numberOfLines(widths []int, s string) []int {
	lines, width := 1, 0
	for _, character := range s {
		next := widths[character-'a']
		if width+next > 100 {
			lines++
			width = next
		} else {
			width += next
		}
	}
	return []int{lines, width}
}
Pythonnumber-of-lines-to-write-string/solution.py
class Solution:
    def numberOfLines(self, widths: list[int], s: str) -> list[int]:
        lines, width = class="syntax-number">1, class="syntax-number">0
        for character in s:
            next_width = widths[ord(character) - ord(class="syntax-string">"a")]
            if width + next_width > class="syntax-number">100: lines, width = lines + class="syntax-number">1, next_width
            else: width += next_width
        return [lines, width]
TypeScriptnumber-of-lines-to-write-string/solution.ts
function numberOfLines(widths: number[], s: string): number[] {
  let lines = class="syntax-number">1;
  let width = class="syntax-number">0;
  for (const character of s) { const next = widths[character.charCodeAt(class="syntax-number">0) - class="syntax-number">97]; if (width + next > class="syntax-number">100) { lines += class="syntax-number">1; width = next; } else width += next; }
  return [lines, width];
}