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 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
๐Ÿ“บ Digital Billboard Sentence FittingBillboard Screen (2 rows ร— 8 cols)hello world hellโœ“ 1 complete sentence displayedAlgorithm Flow:1. Total capacity: 2 ร— 8 = 16 characters2. Sentence length: 'hello world ' = 12 chars3. Adjust for word boundary: position 16 โ†’ 114. Complete sentences: 11 รท 12 = 0, but with wrapping = 1
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!
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
36.3K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen