MediumLeetCode #6

Zigzag Conversion

Learn how to simulate a zigzag traversal using row-based storage and a direction variable instead of building a full matrix.

StringsSimulationArrays

Problem

Zigzag Conversion

The Problem

You are given a string s and an integer numRows.

Write the characters of the string in a zigzag pattern across numRows rows and then read the rows from top to bottom.

For example:

Input:
PAYPALISHIRING
3

The characters are arranged like this:

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

Reading the rows from top to bottom gives:

PAHNAPLSIIGYIR

The important thing to understand is that the spaces shown above are not part of the string.

They only help us visualize the zigzag.


Before You Look at the Hints

Try to solve this problem yourself first.

Don't immediately think about the final optimized code.

Start by asking:

How would I physically arrange these characters into rows?

Then ask:

Do I actually need to build the entire visual matrix?

That second question is where the problem becomes much simpler.


Examples

Example 1

Input

PAYPALISHIRING
3

Output

PAHNAPLSIIGYIR
Example 2

Input

PAYPALISHIRING
4

Output

PINALSIGYAHRPI

YOUR SOLUTION

Try it yourself

Run against the examples first. Submit when you're confident.

solution.cpp
CPP

Ready to run

TEST CASES

Check your thinking

Example 1Test Case

Input

PAYPALISHIRING
3

Expected Output

PAHNAPLSIIGYIR
Example 2Test Case

Input

PAYPALISHIRING
4

Expected Output

PINALSIGYAHRPI

Elvoret Approach

Stuck? Use a hint.

Try the problem yourself first. If you get stuck, reveal the hints one at a time. After all three hints, you can reveal the complete answer.