Sentence Screen Fitting
Problem
Given a screen with rows rows and cols columns, and an array of words sentence, return how many times the sentence fits on the screen end-to-end.
rows = 2, cols = 8, sentence = ["hello","world"]1def words_typing(sentence, rows, cols):
s = " ".join(sentence) + " "
n = len(s)
p = 0
for _ in range(rows):
p += cols
while p > 0 and s[p % n] != " ":
p -= 1
p += 1
return p // n
function wordsTyping(sentence, rows, cols) {
const s = sentence.join(" ") + " ";
const n = s.length;
let p = 0;
for (let i = 0; i < rows; i++) {
p += cols;
while (p > 0 && s[p % n] !== " ") p--;
p++;
}
return Math.floor(p / n);
}
class Solution {
public int wordsTyping(String[] sentence, int rows, int cols) {
String s = String.join(" ", sentence) + " ";
int n = s.length(), p = 0;
for (int i = 0; i < rows; i++) {
p += cols;
while (p > 0 && s.charAt(p % n) != ' ') p--;
p++;
}
return p / n;
}
}
int wordsTyping(vector& sentence, int rows, int cols) {
string s;
for (auto& w : sentence) s += w + " ";
int n = s.size(), p = 0;
for (int i = 0; i < rows; i++) {
p += cols;
while (p > 0 && s[p % n] != ' ') p--;
p++;
}
return p / n;
}
Explanation
Instead of placing words one by one, we treat the sentence as one repeating ribbon of characters and track a single position p that keeps growing as if we typed the sentence over and over forever.
First we build s = " ".join(sentence) + " ", a copy of the sentence with a trailing space, and let n = len(s). The position p counts total characters typed across the whole screen, and p % n tells us where we are inside the repeating sentence.
For each of the rows rows we jump forward by cols characters. If we land in the middle of a word (the character at s[p % n] is not a space), we back up until we hit a space, so words are never split across the row's edge. Then p += 1 steps past that space to start the next row cleanly.
After filling all rows, p is the total number of characters typed, and p // n is how many full copies of the sentence fit, since each full sentence is n characters long.
Example: rows = 2, cols = 8, sentence = ["hello", "world"]. The ribbon is "hello world " of length 12. After processing both rows the position lands at 12, and 12 // 12 = 1, so the sentence fits once.