Sentence Screen Fitting — LeetCode 418 Python Solution

MediumLeetCode PremiumArrayStringDynamic Programming
Problem
#418
Reading time
2 min

The problem

Given a rows x cols screen and a sentence represented as a list of strings, return the number of times the given sentence can be fitted on the screen. The order of words in the sentence must remain unchanged, and a word cannot be split into two lines.

Example

Input
sentence = ["hello","world"], rows = 2, cols = 8
Output
1
Explanation
hello---

Python solution

Python
class Solution:
    def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int:
        s = " ".join(sentence) + " "
        m = len(s)
        cur = 0
        for _ in range(rows):
            cur += cols
            if s[cur % m] == " ":
                cur += 1
            while cur and s[(cur - 1) % m] != " ":
                cur -= 1
        return cur // m

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 418. Sentence Screen Fitting is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 418. Sentence Screen Fitting?
LeetCode 418. Sentence Screen Fitting is rated Medium on LeetCode.
What topics does LeetCode 418. Sentence Screen Fitting cover?
LeetCode 418. Sentence Screen Fitting is tagged Array, String and Dynamic Programming on LeetCode.
Is LeetCode 418. Sentence Screen Fitting a premium problem?
Yes. LeetCode 418. Sentence Screen Fitting is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview