Skip to content

Commit 0cfbfc7

Browse files
authored
Create max width.py
1 parent 92f1d91 commit 0cfbfc7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

interview_query/max width.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
'''
3+
Given an array of words and a max_width parameter, write a function justify to format the text such that each line has exactly max_width characters. Pad extra spaces ’ ‘ when necessary so that each line has exactly max_width characters.
4+
5+
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, place excess spaces on the right-hand side of each line.
6+
7+
Note: You may assume that there is no word in words that is longer than max_width.
8+
'''
9+
10+
11+
def justify(words, max_width):
12+
13+
res = []
14+
cur = []
15+
num_of_letters = 0
16+
17+
for w in words:
18+
if num_of_letters + len(w) + len(cur) > max_width:
19+
for i in range(max_width - num_of_letters):
20+
cur[i % (len(cur) - 1 or 1)] += ' '
21+
res.append(''.join(cur))
22+
cur, num_of_letters = [], 0
23+
cur += [w]
24+
num_of_letters += len(w)
25+
26+
# Treat the last line in the same way as the other lines
27+
for i in range(max_width - num_of_letters):
28+
cur[i % (len(cur) - 1 or 1)] += ' '
29+
res.append(''.join(cur))
30+
31+
return res

0 commit comments

Comments
 (0)