#806
Number of Lines To Write String
EasyArrayStringArrayGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach is similar to the brute-force method but focuses on minimizing unnecessary checks. We keep track of the current line width and only check if we need to start a new line when adding a character, ensuring we only loop through the string once.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a counter for lines and a variable for the current line width.
- 2Step 2: Iterate through each character in the string.
- 3Step 3: For each character, calculate its width using the widths array.
- 4Step 4: If adding the character's width exceeds 100, increment the line counter and reset the current width.
- 5Step 5: Continue adding characters to the current line until all characters are processed.
- 6Step 6: Return the total number of lines and the width of the last line.
solution.py11 lines
1def numberOfLines(widths, s):
2 lines = 1
3 current_width = 0
4 for char in s:
5 width = widths[ord(char) - ord('a')]
6 if current_width + width > 100:
7 lines += 1
8 current_width = width
9 else:
10 current_width += width
11 return [lines, current_width]ℹ
Complexity note: The optimal solution runs in O(n) time because we only traverse the string once, making it efficient for longer strings.
- 1Each character's width is determined by its position in the alphabet.
- 2The maximum width of a line is capped at 100 pixels.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.