VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-number-of-times-given-sentence-can-be-fitted-on-screen/

⇱ Count number of times given sentence can be fitted on screen - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count number of times given sentence can be fitted on screen

Last Updated : 11 Jun, 2024

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:

  • The order of words in the sentence must remain unchanged.
  • A word cannot be split across two lines.
  • A single space must separate two consecutive words in a line.

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:

  • Create a single string from the sentence with spaces separating the words. Add a trailing space to handle edge cases easily.
  • Set up a pointer to track the position in the concatenated string.
  • For each row, move the pointer cols positions ahead.
    • If the pointer lands on a space, move forward to the start of the next word. If it lands in the middle of a word, move back to the start of the current word.
    • Keep track of how many times the pointer completes a full traversal of the concatenated string in result.
  • Return the result

Below is the implementation of the above approach:


Output
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.


Comment