Problem Description
Given a screen with a specified number of rows and columns, and a sentence as a list of words, determine how many times the entire sentence can be fitted on the screen. Words cannot be split between lines, and a single space is required between consecutive words. The order of the words must remain unchanged.
Key Insights
- Concatenate the words of the sentence into a single string with spaces (and an extra space at the end) to simulate continuous placement.
- Use modulo arithmetic to simulate wrapping around the sentence.
- For each row, determine how many characters (including spaces) can be placed. If placement ends in the middle of a word, adjust the pointer so that the word is not split.
- The total count divided by the length of the concatenated string indicates how many times the sentence fits on the screen.
Space and Time Complexity
Time Complexity: O(rows) – We iterate through each row, and adjustments inside the loop are done in constant time on average. Space Complexity: O(1) – Only a few extra variables are used regardless of input size.
Solution
The solution first forms a concatenated string from the sentence with an extra space at the end. This string represents the ideal continuous "line" of text if the sentence were repeated ad infinitum. For each row, we simulate filling columns by adding the number of columns to a pointer that tracks the current position in this long string.
If the pointer lands on a space, we can move to the next character safely. If not, we backtrack to ensure that we are not breaking a word. This adjustment is necessary because words cannot be split between rows. After processing all rows, the number of times the sentence has been fully displayed is equal to the integer division of the pointer by the length of the concatenated sentence string.
Key data structures and techniques:
- String manipulation for concatenation.
- Looping through rows.
- Modulo arithmetic to simulate cyclic iteration over the string.
- Pointer adjustments to ensure word boundaries.