1
# Runtime: 96 ms (Top 61.23%) | Memory: 14 MB (Top 75.15%)
2
class Solution:
3
def convert(self, s: str, numRows: int) -> str:
4

5
# safety check to not process single row
6
if numRows == 1:
7
return s
8

9
# safety check to not process strings shorter/equal than numRows
10
if len(s) <= numRows:
11
return s
12

13
# safety check to not process double rows
14
if numRows == 2:
15
# slice every other character
16
return s[0::2] + s[1::2]
17

18
# list that stores the lines
19
# add lines with initial letters
20
lines: list[str] = [letter for letter in s[:numRows]]
21

22
# positive direction goes down
23
# lines are created, so it's going up
24
direction: int = -1
25

26
# track the position at which the letter will be added
27
# position after bouncing off, after adding initial lines
28
line_index: int = numRows - 2
29

30
# edge indexes
31
# 0 can only be reached by going up
32
# numRows only by going down
33
edges: set[int] = {0, numRows}
34

35
for letter in s[numRows:]:
36
# add letter at tracked index position
37
lines[line_index] += letter
38

39
# prepare index before next loop iteration
40
line_index += direction
41

42
# reaching one of the edges
43
if line_index in edges:
44
# change direction
45
direction = -direction
46
# bounce off if bottom edge
47
if line_index == numRows:
48
line_index += direction * 2
49

50
return "".join(lines)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0