ExamAdda Logo

Zigzag Conversion

Easy

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows.

For example, with numRows = 3, the pattern is:

P   A   H   N
A P L S I I G
Y   I   R

After reading the pattern row by row, the converted string becomes "PAHNAPLSIIGYIR".

Given a string s and an integer numRows, return the string obtained after writing the characters in a zigzag pattern and then reading them row by row.

Example 1

Input

PAYPALISHIRING
3

Output

PAHNAPLSIIGYIR

Explanation

Writing the string in a zigzag pattern with 3 rows and reading row by row produces "PAHNAPLSIIGYIR".

Example 2

Input

PAYPALISHIRING
4

Output

PINALSIGYAHRPI

Explanation

After arranging the characters in 4 zigzag rows and reading row by row, the resulting string is "PINALSIGYAHRPI".

Constraints

1 ≤ s.length ≤ 1000
1 ≤ numRows ≤ 1000
s consists of English letters
'
' and '.'.

Hints:

Hint 1

Simulate writing the characters row by row while moving downward and then upward repeatedly.

Hint 2

Maintain a string for each row. Append each character to its corresponding row, then concatenate all rows to form the final answer.

Author & Technical Reviewer

Chatla Jithin Sri Surya

Technically reviewed by: Chatla Jithin Sri Surya

Content Writer

<p>IIEST Shibpur | SDE | AI, ML &amp; Gen AI | DSA | Building Intelligent, Scalable Software</p>

Published

Oct 19, 2026

Last updated

Oct 19, 2026

Last technically reviewed

Oct 19, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output