Count number of times given sentence can be fitted on screen (original) (raw)

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:

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

Step-by-Step Approach:

Below is the implementation of the above approach:

C++ `

#include #include #include

using namespace std;

int wordsTyping(vector& sentence, int rows, int cols) { // Concatenate the sentence into a single string with // spaces string allWords = ""; for (const string& word : sentence) { allWords += word + " "; }

int length = allWords.size();
int pointer = 0;

// Simulate each row
for (int i = 0; i < rows; ++i) {
    pointer
        += cols; // Move pointer cols positions ahead

    // If the pointer is at a space, move to the next
    // word
    if (allWords[pointer % length] == ' ') {
        pointer++;
    }
    // If the pointer is in the middle of a word, move
    // back to the start of the word
    else {
        while (pointer > 0
               && allWords[(pointer - 1) % length]
                      != ' ') {
            pointer--;
        }
    }
}

// Number of times the sentence is fitted
return pointer / length;

}

// Driver code int main() { vector sentence1 = { "hello", "world" }; int rows1 = 2, cols1 = 8; cout << wordsTyping(sentence1, rows1, cols1) << endl; // Output: 1

return 0;

}

`

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