The Number of Lines To Write String problem gives you a string and a width array widths[26] specifying the pixel width of each letter. You write the string on lines of width 100 pixels. When a word doesn't fit on the current line, wrap to the next. Count the total number of lines and the width used in the last line. This coding problem tests straightforward greedy string packing.
Google asks this easy problem to verify greedy word-wrapping implementation skills. It tests clean loop logic for tracking current line width and wrapping conditions. The array and string interview pattern is demonstrated here with practical text-formatting relevance.
Greedy line packing. Maintain lines = 1 and current_width = 0. For each character c: if current_width + widths[c - 'a'] > 100, wrap: increment lines, reset current_width to widths[c-'a']. Otherwise, add widths[c-'a'] to current_width.
widths = [10]*26 (all letters = 10 pixels). s = "abcdefghij" (10 chars). Each char = 10 pixels. 10 chars * 10 = 100 pixels = exactly one full line. Result: [1, 100] (1 line, last line width = 100).
s = "abcdefghijk" (11 chars): first 10 fill 100 pixels (line 1). 11th char 'k' wraps to line 2: width = 10. Result: [2, 10].
lines = 0 instead of lines = 1.current_width + next >= 100 vs > 100 (≤ 100 fits on current line).c - 'a').String line-wrapping problems follow a simple greedy template: maintain current line width, wrap when the next character would exceed the limit. The boundary condition (≤ 100 fits, > 100 wraps) is the most error-prone part — test it with a character that would fill the line exactly to 100. Practice similar text-justification problems to build confidence in line-packing greedy logic.