KatInterview

824. Number of Lines To Write String

EasySolutions 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

Method Explanation

This problem asks us to simulate writing a string s onto lines with a maximum width of 100 pixels. We need to find the total number of lines used and the width of the last line. The process is greedy, meaning we fit as many characters as possible on each line.

Solution

Number of Lines To Write String in Python

class Solution:
    def numberOfLines(self, widths: list[int], s: str) -> list[int]:
        # Maximum width of a line
        MAX_WIDTH = 100
        
        # lines: total number of lines used. Start with 1 as s is not empty.
        # current_width: width of the current line being written to.
        lines = 1
        current_width = 0
        
        # Iterate through each character in the string s
        for char in s:
            # Calculate the width of the current character. ord(char) - ord('a') gives the index.
            char_width = widths[ord(char) - ord('a')]
            
            # Check if adding the current character exceeds the max width
            if current_width + char_width > MAX_WIDTH:
                # If it does, we need to start a new line
                lines += 1
                # The new line starts with the current character
                current_width = char_width
            else:
                # If it fits, add its width to the current line
                current_width += char_width
                
        # Return the total number of lines and the width of the last line
        return [lines, current_width]

Number of Lines To Write String in Java

class Solution {
    public int[] numberOfLines(int[] widths, String s) {
        // Maximum width of a line
        final int MAX_WIDTH = 100;
        
        // lines: total number of lines used. Start with 1 as s is not empty.
        // currentWidth: width of the current line being written to.
        int lines = 1;
        int currentWidth = 0;
        
        // Iterate through each character in the string s
        for (char c : s.toCharArray()) {
            // Calculate the width of the current character
            int charWidth = widths[c - 'a'];
            
            // Check if adding the current character exceeds the max width
            if (currentWidth + charWidth > MAX_WIDTH) {
                // If it does, we need to start a new line
                lines++;
                // The new line starts with the current character
                currentWidth = charWidth;
            } else {
                // If it fits, add its width to the current line
                currentWidth += charWidth;
            }
        }
        
        // Return the total number of lines and the width of the last line
        return new int[]{lines, currentWidth};
    }
}

Number of Lines To Write String in C++

class Solution {
public:
    vector<int> numberOfLines(vector<int>& widths, string s) {
        // Maximum width of a line
        const int MAX_WIDTH = 100;
        
        // lines: total number of lines used. Start with 1 as s is not empty.
        // currentWidth: width of the current line being written to.
        int lines = 1;
        int currentWidth = 0;
        
        // Iterate through each character in the string s
        for (char c : s) {
            // Calculate the width of the current character
            int charWidth = widths[c - 'a'];
            
            // Check if adding the current character exceeds the max width
            if (currentWidth + charWidth > MAX_WIDTH) {
                // If it does, we need to start a new line
                lines++;
                // The new line starts with the current character
                currentWidth = charWidth;
            } else {
                // If it fits, add its width to the current line
                currentWidth += charWidth;
            }
        }
        
        // Return the total number of lines and the width of the last line
        return {lines, currentWidth};
    }
};

Number of Lines To Write String in TypeScript

function numberOfLines(widths: number[], s: string): number[] {
    // Maximum width of a line
    const MAX_WIDTH = 100;
    
    // lines: total number of lines used. Start with 1 as s is not empty.
    // currentWidth: width of the current line being written to.
    let lines = 1;
    let currentWidth = 0;
    
    // Iterate through each character in the string s
    for (let i = 0; i < s.length; i++) {
        const char = s[i];
        // Calculate the width of the current character.
        // char.charCodeAt(0) - 'a'.charCodeAt(0) gives the index.
        const charWidth = widths[char.charCodeAt(0) - 'a'.charCodeAt(0)];
        
        // Check if adding the current character exceeds the max width
        if (currentWidth + charWidth > MAX_WIDTH) {
            // If it does, we need to start a new line
            lines++;
            // The new line starts with the current character
            currentWidth = charWidth;
        } else {
            // If it fits, add its width to the current line
            currentWidth += charWidth;
        }
    }
    
    // Return the total number of lines and the width of the last line
    return [lines, currentWidth];
};

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.