Sentence Screen Fitting - Problem
Sentence Screen Fitting - Imagine you're building a text editor that needs to display text on a fixed-size screen!
Given a screen with
Rules:
Goal: Return the total number of times the complete sentence can be displayed on the screen.
Example: With sentence
Given a screen with
rows ร cols dimensions and a sentence represented as an array of words, your task is to determine how many complete sentences can fit on the screen.Rules:
- Words must appear in their original order
- Words cannot be split across lines
- Single spaces must separate consecutive words
- If a word is too long for a line, move it to the next line
Goal: Return the total number of times the complete sentence can be displayed on the screen.
Example: With sentence
["hello", "world"] and a 2ร8 screen, you might fit: "hello wo" on row 1, "rld hell" on row 2, completing 1 full sentence. Input & Output
example_1.py โ Basic Case
$
Input:
sentence = ["hello", "world"], rows = 2, cols = 8
โบ
Output:
1
๐ก Note:
Row 1: 'hello wo' (8 chars), Row 2: 'rld hell' (8 chars). We fit 'hello world' once completely, with 'hell' starting the next sentence.
example_2.py โ Multiple Sentences
$
Input:
sentence = ["a", "bcd", "e"], rows = 3, cols = 6
โบ
Output:
2
๐ก Note:
Row 1: 'a bcd ' (6 chars), Row 2: 'e a bc' (6 chars), Row 3: 'd e a ' (6 chars). We complete 'a bcd e' twice.
example_3.py โ Word Too Long
$
Input:
sentence = ["hello", "leetcode"], rows = 1, cols = 7
โบ
Output:
0
๐ก Note:
The word 'leetcode' has 8 characters but each row only has 7 columns, so it cannot fit and no complete sentences are possible.
Constraints
- 1 โค rows, cols โค 2 ร 104
- 1 โค sentence.length โค 100
- 1 โค sentence[i].length โค 10
- sentence[i] consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Prepare Text Stream
Convert sentence into repeating character stream: 'hello world hello world...'
2
Fill Screen Capacity
Calculate total characters that can fit: rows ร cols
3
Respect Word Boundaries
Adjust position to avoid breaking words across lines
4
Count Complete Cycles
Divide total valid characters by sentence length
Key Takeaway
๐ฏ Key Insight: Instead of simulating each word placement, treat the problem as filling a character buffer from an infinite text stream, then adjusting for word boundaries. This mathematical approach scales beautifully!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code