{x}
blog image

Number of Lines To Write String

You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.

You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.

Return an array result of length 2 where:

  • result[0] is the total number of lines.
  • result[1] is the width of the last line in pixels.

 

Example 1:

Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz"
Output: [3,60]
Explanation: You can write s as follows:
abcdefghij  // 100 pixels wide
klmnopqrst  // 100 pixels wide
uvwxyz      // 60 pixels wide
There are a total of 3 lines, and the last line is 60 pixels wide.

Example 2:

Input: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "bbbcccdddaaa"
Output: [2,4]
Explanation: You can write s as follows:
bbbcccdddaa  // 98 pixels wide
a            // 4 pixels wide
There are a total of 2 lines, and the last line is 4 pixels wide.

 

Constraints:

  • widths.length == 26
  • 2 <= widths[i] <= 10
  • 1 <= s.length <= 1000
  • s contains only lowercase English letters.

Solution Explanation: Number of Lines to Write String

This problem involves calculating the number of lines needed to write a given string, s, considering the width of each character specified in the widths array. Each line has a maximum width of 100 pixels.

Approach:

The most efficient way to solve this problem is through a single pass simulation. We iterate through the input string, character by character, keeping track of the current line's width. If adding the current character's width exceeds the 100-pixel limit, we increment the line count and start a new line.

Algorithm:

  1. Initialization:

    • lines: Initialize a counter for the number of lines to 1 (we start with one line).
    • last: Initialize a variable to store the width of the last line to 0.
  2. Iteration:

    • Iterate through each character c in the input string s.
    • Get the width w of the character c from the widths array using the character's ASCII value (e.g., widths[c - 'a'] in many languages).
    • Check if adding w to the current last line's width exceeds 100 pixels (last + w > 100).
      • If it exceeds 100, increment lines (start a new line), and reset last to w (the new line starts with the current character's width).
      • Otherwise, add w to last (add the character to the current line).
  3. Result:

    • After iterating through all characters, return an array [lines, last], containing the total number of lines and the width of the last line.

Time and Space Complexity:

  • Time Complexity: O(n), where n is the length of the input string s. We iterate through the string once.
  • Space Complexity: O(1). We use a constant amount of extra space to store variables (lines, last).

Code Implementation (Python):

def numberOfLines(widths, s):
    lines = 1
    last_line_width = 0
    for char in s:
        char_width = widths[ord(char) - ord('a')]
        if last_line_width + char_width <= 100:
            last_line_width += char_width
        else:
            lines += 1
            last_line_width = char_width  # Start a new line
    return [lines, last_line_width]
 

Code Implementation (Java):

class Solution {
    public int[] numberOfLines(int[] widths, String s) {
        int lines = 1;
        int lastLineWidth = 0;
        for (char c : s.toCharArray()) {
            int charWidth = widths[c - 'a'];
            if (lastLineWidth + charWidth <= 100) {
                lastLineWidth += charWidth;
            } else {
                lines++;
                lastLineWidth = charWidth;
            }
        }
        return new int[]{lines, lastLineWidth};
    }
}

Code Implementation (C++):

vector<int> numberOfLines(vector<int>& widths, string s) {
    int lines = 1;
    int lastLineWidth = 0;
    for (char c : s) {
        int charWidth = widths[c - 'a'];
        if (lastLineWidth + charWidth <= 100) {
            lastLineWidth += charWidth;
        } else {
            lines++;
            lastLineWidth = charWidth;
        }
    }
    return {lines, lastLineWidth};
}

The other languages (JavaScript, Go, TypeScript, Rust) would follow a very similar structure, adapting the syntax to the specific language but maintaining the core algorithm. The key is the efficient single-pass iteration and the logic for handling line breaks.