![]() |
VOOZH | about |
Given a screen with dimensions rows*cols, and a sentence represented as a list of strings. The task is to return the number of times the given sentence can be fitted on the screen.
The following constraints must be met:
Example:
Input: sentence = ["hello","world"], rows = 2, cols = 8
Output: 1
Explanation:
hello---
world---
The character '-' signifies an empty space on the screen.Input: sentence = ["a", "bcd", "e"], rows = 3, cols = 6
Output: 2
Explanation:
a-bcd-
e-a---
bcd-e-
The character '-' signifies an empty space on the screen.
Approach:
The core idea is to keep track of how much of the sentence we can fit in each row, and count the number of times the complete sentence is fitted.
- Concatenate all the words in the sentence into a single string with spaces in between. This makes it easier to visualize the fitting process.
- Simulate the fitting process row by row:
- Use a pointer to keep track of the position in the concatenated string.
- For each row, try to fit as many characters from the current position as possible.
- Adjust the pointer correctly if it lands on a space or between words to ensure words are not split.
- Calculate how many times the pointer wraps around the concatenated string.
Step-by-Step Approach:
cols positions ahead.Below is the implementation of the above approach:
1
Time Complexity: O(rows*cols), as we potentially iterate through each cell in the screen.
Auxiliary Space Complexity: O(1), since we use a fixed amount of extra space regardless of the input size.