Number of Lines To Write String
Real-world version: Rows Needed to Set the NoticeThe statement here is our own: the same inputs, outputs and technique.
A typesetter fills rows exactly 100 units wide. Letter 'a' takes widths[0] units, letter 'b' takes widths[1], and so on through the alphabet.
The letters of s are set in order. A letter goes on the current row when it still fits within 100 units; otherwise a new row is started and the letter goes at its beginning. No letter is ever split across two rows.
Return a list of two numbers: how many rows were used, and how many units the last row holds.
Examples
Example 1
- Input
- widths = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10], s = "abcdefghijk"
- Output
- [2, 10]
Every letter takes 10 units, so ten of them exactly fill the first row and the eleventh starts a second row holding 10 units.
Example 2
- Input
- widths = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], s = "a"
- Output
- [1, 2]
A single letter of width 2 sits on the first row, which then holds 2 units.
Example 3
- Input
- widths = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- Output
- [2, 2]
Fifty letters of width 2 fill the first row exactly, so the fifty-first starts a second row.
Constraints
- widths.length == 26
- 2 <= widths[i] <= 10
- 1 <= s.length <= 1000
- s consists of lowercase English letters only
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def rows_needed(widths: list[int], s: str) -> list[int]:public int[] rowsNeeded(int[] widths, String s)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Longest Common PrefixReal-world version: Shared Crate CodeEasy
- Shortest Word DistanceReal-world version: Closest Station Calls in the Announcement LogEasy
- Verifying an Alien DictionaryReal-world version: Catalogue Order Under a Custom Glyph SequenceEasy
- Find Common CharactersReal-world version: Tiles Every Rack Can SupplyEasy