KatInterview

418. Sentence Screen Fitting

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to calculate how many times a given sentence can be completely typed on a screen of size rows by cols. The words of the sentence must be typed in order, cannot be split across lines, and must be separated by a single space. The sentence can be typed repeatedly.

Solution

Sentence Screen Fitting in Python

class Solution:
    def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int:
        n = len(sentence)
        if n == 0:
            return 0

        # dp[i] stores the number of words that can be fit on one line
        # if the line starts with sentence[i].
        dp = [0] * n

        # Precomputation phase
        for i in range(n):
            current_len = 0
            words_on_line = 0
            word_idx = i

            # Simulate filling one line starting with sentence[i]
            while True:
                space_needed = 1 if words_on_line > 0 else 0
                if current_len + space_needed + len(sentence[word_idx]) <= cols:
                    current_len += space_needed + len(sentence[word_idx])
                    words_on_line += 1
                    word_idx = (word_idx + 1) % n
                else:
                    break
            dp[i] = words_on_line

        # Simulation phase
        total_words_placed = 0
        current_word_idx = 0
        for _ in range(rows):
            # For the current row starting with current_word_idx,
            # we can place dp[current_word_idx] words.
            words_this_row = dp[current_word_idx]
            if words_this_row == 0: # A word is too long, impossible to fit
                return 0
            total_words_placed += words_this_row
            
            # Update the starting word index for the next row
            current_word_idx = (current_word_idx + words_this_row) % n

        # The result is the number of full sentences placed.
        return total_words_placed // n

Sentence Screen Fitting in Java

class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        int n = sentence.length;
        if (n == 0) {
            return 0;
        }

        // dp[i] stores the number of words that can be fit on one line
        // if the line starts with sentence[i].
        int[] dp = new int[n];

        // Precomputation phase
        for (int i = 0; i < n; i++) {
            int currentLen = 0;
            int wordsOnLine = 0;
            int wordIdx = i;

            // Simulate filling one line starting with sentence[i]
            while (true) {
                int spaceNeeded = (wordsOnLine > 0) ? 1 : 0;
                if (currentLen + spaceNeeded + sentence[wordIdx].length() <= cols) {
                    currentLen += spaceNeeded + sentence[wordIdx].length();
                    wordsOnLine++;
                    wordIdx = (wordIdx + 1) % n;
                } else {
                    break;
                }
            }
            dp[i] = wordsOnLine;
        }

        // Simulation phase
        int totalWordsPlaced = 0;
        int currentWordIdx = 0;
        for (int r = 0; r < rows; r++) {
            // For the current row starting with currentWordIdx,
            // we can place dp[currentWordIdx] words.
            int wordsThisRow = dp[currentWordIdx];
             if (wordsThisRow == 0) { // A word is too long, impossible to fit
                return 0;
            }
            totalWordsPlaced += wordsThisRow;

            // Update the starting word index for the next row
            currentWordIdx = (currentWordIdx + wordsThisRow) % n;
        }

        // The result is the number of full sentences placed.
        return totalWordsPlaced / n;
    }
}

Sentence Screen Fitting in C++

class Solution {
public:
    int wordsTyping(vector<string>& sentence, int rows, int cols) {
        int n = sentence.size();
        if (n == 0) {
            return 0;
        }

        // dp[i] stores the number of words that can be fit on one line
        // if the line starts with sentence[i].
        vector<int> dp(n);
        
        // Precomputation phase
        for (int i = 0; i < n; ++i) {
            int current_len = 0;   // Current length of words on the line
            int words_on_line = 0; // Number of words placed on the line
            int word_idx = i;      // Current word index in the sentence

            // Simulate filling one line starting with sentence[i]
            while (true) {
                int space_needed = (words_on_line > 0) ? 1 : 0;
                if (current_len + space_needed + sentence[word_idx].length() <= cols) {
                    current_len += space_needed + sentence[word_idx].length();
                    words_on_line++;
                    word_idx = (word_idx + 1) % n;
                } else {
                    break;
                }
            }
            dp[i] = words_on_line;
        }

        // Simulation phase
        int total_words_placed = 0;
        int current_word_idx = 0;
        for (int r = 0; r < rows; ++r) {
            // For the current row starting with current_word_idx,
            // we can place dp[current_word_idx] words.
            int words_this_row = dp[current_word_idx];
            if (words_this_row == 0) { // A word is too long, impossible to fit
                return 0;
            }
            total_words_placed += words_this_row;
            
            // Update the starting word index for the next row
            current_word_idx = (current_word_idx + words_this_row) % n;
        }

        // The result is the number of full sentences placed.
        return total_words_placed / n;
    }
};

Sentence Screen Fitting in TypeScript

function wordsTyping(sentence: string[], rows: number, cols: number): number {
    const n = sentence.length;
    if (n === 0) {
        return 0;
    }

    // dp[i] stores the number of words that can be fit on one line
    // if the line starts with sentence[i].
    const dp: number[] = new Array(n).fill(0);

    // Precomputation phase
    for (let i = 0; i < n; i++) {
        let currentLen = 0;
        let wordsOnLine = 0;
        let wordIdx = i;

        // Simulate filling one line starting with sentence[i]
        while (true) {
            const spaceNeeded = wordsOnLine > 0 ? 1 : 0;
            if (currentLen + spaceNeeded + sentence[wordIdx].length <= cols) {
                currentLen += spaceNeeded + sentence[wordIdx].length;
                wordsOnLine++;
                wordIdx = (wordIdx + 1) % n;
            } else {
                break;
            }
        }
        dp[i] = wordsOnLine;
    }

    // Simulation phase
    let totalWordsPlaced = 0;
    let currentWordIdx = 0;
    for (let r = 0; r < rows; r++) {
        // For the current row starting with currentWordIdx,
        // we can place dp[currentWordIdx] words.
        const wordsThisRow = dp[currentWordIdx];
        if (wordsThisRow === 0) { // A word is too long, impossible to fit
            return 0;
        }
        totalWordsPlaced += wordsThisRow;

        // Update the starting word index for the next row
        currentWordIdx = (currentWordIdx + wordsThisRow) % n;
    }

    // The result is the number of full sentences placed.
    return Math.floor(totalWordsPlaced / n);
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.