File: number-of-lines-to-write-string/solution.py

Date: 2026-06-06

Time: 18:19

Purpose

This file solves LeetCode 806 — Number of Lines To Write String. It simulates writing a string character-by-character across lines that are each at most 100 pixels wide, then reports how many lines were used and how wide the last line is.

The method name numberOfWays is a misnomer — it should be numberOfLines per the LeetCode problem. This doesn't affect correctness since LeetCode matches by class/method signature, but it's misleading to readers.

Key Components

Solution.numberOfWays(widths, s) — The single method. Takes a 26-element list mapping each letter az to its pixel width, plus a string s to write. Returns [lines, lastlinewidth].

Flow

1. Start with lines = 1, current_width = 0.

2. For each character in s:

3. Return the line count and final line width.

The key decision point is current_width + w > 100 — a character that would push past the 100-pixel boundary forces a line break *before* itself. A character that lands exactly on 100 does not.

Patterns

Dependencies

Invariants

Error Handling

None. The code trusts its inputs completely, which is appropriate for a LeetCode solution where constraints are guaranteed by the judge.

Topics to Explore

Beliefs