Sentence Screen Fitting - Problem

Given a rows × 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. A single space must separate two consecutive words in a line.

Constraints:

  • A word can only be placed on a line if it fits completely
  • Words must appear in order
  • Each line can contain multiple words separated by single spaces
  • Count how many complete sentences fit on the screen

Input & Output

Example 1 — Basic Case
$ Input: sentence = ["hello", "world"], rows = 2, cols = 8
Output: 1
💡 Note: Row 1: "hello wo" (8 chars), Row 2: "rld hello" (9 chars, but only 8 fit: "rld hell"). One complete sentence "hello world" fits.
Example 2 — Multiple Sentences
$ Input: sentence = ["a", "bcd", "e"], rows = 3, cols = 6
Output: 2
💡 Note: Row 1: "a bcd e" (7 chars, fits as "a bcd "), Row 2: "e a bcd" (7 chars, fits as "e a bc"), Row 3: "d e a b" (7 chars, fits as "d e a "). Two complete sentences fit.
Example 3 — Single Long Word
$ Input: sentence = ["hello-world"], rows = 1, cols = 10
Output: 0
💡 Note: The word "hello-world" has 11 characters but column limit is 10, so it cannot fit at all.

Constraints

  • 1 ≤ sentence.length ≤ 100
  • 1 ≤ sentence[i].length ≤ 80
  • sentence[i] consists of only lowercase English letters
  • 1 ≤ rows, cols ≤ 2 × 104

Visualization

Tap to expand
Sentence Screen Fitting INPUT sentence array: "hello" "world" [0] [1] Screen (2 rows x 8 cols): 1 2 3 4 5 6 7 8 Parameters: rows = 2 cols = 8 words = 2 ALGORITHM STEPS 1 Join Sentence "hello world " (len=12) 2 Process Each Row Track position in sentence 3 Memoize Start Positions Cache row transitions 4 Count Completions Total chars / sentence len Memo Table: Row 1: "hello wo" pos=0 next_pos=6 Row 2: "rld hell" pos=6 |hello wo| |rld | world split at row end FINAL RESULT Fitted Screen: hello wo rld Row 1 Row 2 Words placed: hello + world = 1 complete sentence Output: 1 Verification: 1 full sentence fits in 2x8 screen - OK Key Insight: Memoization optimizes by caching what happens when a row starts at each position in the sentence. Since there are only len(sentence) unique starting positions, we avoid recalculating row fills. Time complexity: O(rows + sentence_length * cols) instead of O(rows * cols). TutorialsPoint - Sentence Screen Fitting | Optimized with Memoization
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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