AlgoInsight

DSA problem

Zigzag Conversion

MediumStringsPattern: Simulationtop300AmazonGoogle

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows, then read line by line to produce "PAHNAPLSIIGYIR".

Write the code that will take a string and make this conversion given a number of rows: convert(string s, int numRows).

The characters are placed going down the rows, then diagonally up, then down again, repeating until the string is consumed. The final answer concatenates the rows from top to bottom.

Examples

Example 1
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Explanation: Writing the string in a 3-row zigzag and reading row by row gives "PAHNAPLSIIGYIR".
Example 2
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation: With 4 rows the zigzag has two diagonal characters between vertical segments, producing "PINALSIGYAHRPI".
Example 3
Input: s = "A", numRows = 1
Output: "A"
Explanation: With a single row there is no zigzag, so the output equals the input.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringsimulation

Browse all DSA problems