You want to print a string s of lowercase letters on lines that are each at most 100 pixels wide. The array widths has 26 numbers: widths[0] is how many pixels the letter a takes, widths[1] is for b, and so on up to z.
Fill the lines greedily: put letters on the current line in order for as long as the line stays within 100 pixels. When the next letter would not fit, it starts a new line. Return a pair: the number of lines used, and the width in pixels of the last line.
Example 1
Input: widths = [10,9,8,7,6,5,4,3,2,10,9,8,7,6,5,4,3,2,10,9,8,7,6,5,4,3],
s = "abjkstabjkc"
Output: [2, 8]
Why: the first ten letters use 95 px; c (8 px) would make 1032 more examples and the constraints
Example 2
Input: widths = (same as Example 1), s = "z" Output: [1, 3] Why: one letter on one line, and z is 3 px wide
Example 3
Input: widths = (same as Example 1), s = "aaaaaaaaaa" Output: [1, 100] Why: ten 10 px letters fill one line exactly
Constraints
- 1 ≤ s.length ≤ 1,000
- s contains only lowercase English letters
- widths holds exactly 26 numbers, each between 2 and 10
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Write the lines outO(n)
- Two countersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Steps for a 1,000-letter string | Verdict |
|---|---|---|---|
| Write the lines out | O(n) | Passes; stores text it never needs | |
| Two counters | O(n) | Best; two numbers, one pass |
n = the length of s.
Edge cases to test
- A line filled exactly. A width of exactly 100 still fits. Only going over 100 starts a new line.
- A single letter. One line, and its width is that letter's width.
- The first line is never empty. Start at
lines = 1, not 0, because s has at least one letter. - Long strings. 1,000 letters of width 10 need exactly 100 full lines; the last width is 100, not 0.
Common mistakes
- Using
>= 100to start a new line, which wrongly splits a line that is exactly full. - Setting
width = 0on a new line and forgetting to add the letter that opened it. - Indexing
widthsby the character code without subtracting the code ofa.
How to talk through it
- 1Clarify. Is a line of exactly 100 pixels allowed? Can a single letter ever be wider than a line?
- 2Describe the greedy rule. Letters go in order, so each letter either fits on the current line or starts the next one.
- 3Name the state. Only the line count and the current line's width matter; the text itself does not.
- 4Give the cost. One pass over s, O(n) time and O(1) space.
- 5Test out loud. Try a line that ends at exactly 100 and one that would end at 101.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?