Isaac Emmanuel
09 Sept 2026•EasyGo / Python / TypeScript

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
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}
}
Python•number-of-lines-to-write-string/solution.py
class Solution:
    def numberOfLines(self, widths: list[int], s: str) -> list[int]:
        lines, width = 1, 0
        for character in s:
            next_width = widths[ord(character) - ord("a")]
            if width + next_width > 100: lines, width = lines + 1, next_width
            else: width += next_width
        return [lines, width]
TypeScript•number-of-lines-to-write-string/solution.ts
function numberOfLines(widths: number[], s: string): number[] {
  let lines = 1;
  let width = 0;
  for (const character of s) { const next = widths[character.charCodeAt(0) - 97]; if (width + next > 100) { lines += 1; width = next; } else width += next; }
  return [lines, width];
}