Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-155

Zigzag Conversion

Problem

Write the string s in a zigzag pattern across num_rows rows and read it back row by row.

Track the current row and a direction that flips at the top and bottom rows. If num_rows is 1 or not smaller than the string length, the original string is returned.

Hint

The direction is updated before moving to the next row, so it flips exactly at the edges.

Test cases

case 1
in: ["PAYPALISHIRING",3]
expected: "PAHNAPLSIIGYIR"
case 2
in: ["PAYPALISHIRING",4]
expected: "PINALSIGYAHRPI"
case 3
in: ["A",1]
expected: "A"
case 4
in: ["",3]
expected: ""
case 5
in: ["AB",1]
expected: "AB"
Starter codePython
def zigzag_conversion(s, num_rows):
    # Your code here
    pass

5 test cases · run your code against them in the editor