You are given a list widths, where widths[0] is the width of 'a', widths[1] is the width of 'b', and so on up to widths[25] which is the width of 'z'. You are also given a string S.
Write a function numberOfLines(widths, S) that returns two integers: the number of lines needed to write the string S and the width of the last line. The width of each line must not exceed 100 units.
S be empty?
S is non-empty.lines) and the current width of the last line (current_width).S.widths list.current_width will exceed the limit of 100 units.
lines by 1 and reset current_width to the current character’s width.current_width.def numberOfLines(widths, S):
lines, current_width = 1, 0
for char in S:
char_width = widths[ord(char) - ord('a')]
if current_width + char_width > 100:
lines += 1
current_width = char_width
else:
current_width += char_width
return [lines, current_width]
# Example usage
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"
print(numberOfLines(widths, S)) # Output: [3, 60]
The time complexity of this solution is O(n), where n is the length of the string S. Each character in the string is visited exactly once.
The space complexity is O(1) since we are using a fixed amount of extra space regardless of the input size. The widths list is always of constant size 26, and we only use a few additional variables for counting.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?