Skip to main content
Back to problems
Leetcode
Medium
Arrays
Strings
Simulation
Zigzag Conversion

Rearrange a string by writing its characters in a zigzag pattern across a given number of rows, then read row by row.

Acceptance 0%
Problem Statement

Given a string and a number of rows, write the characters in a zigzag pattern across the rows by moving downward and then diagonally upward repeatedly. After placing all characters, read the pattern row by row to form the final converted string.

Your task is to return that converted string.

This is a string arrangement problem where the main challenge is tracking which row each character belongs to as the zigzag repeats.

Input Format

  • A string s
  • An integer numRows

Output Format

  • Return the zigzag-converted string produced by reading the rows from top to bottom.

Constraints

  • 1 <= s.length
  • 1 <= numRows
  • Characters are processed in order from left to right.
  • If numRows == 1 or numRows >= s.length, the result is the original string.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "PAYPALISHIRING", numRows = 3

Output

"PAHNAPLSIIGYIR"

Explanation

The characters are arranged in 3 rows in a zigzag shape, then concatenated row by row.

Example 2

Input

s = "PAYPALISHIRING", numRows = 4

Output

"PINALSIGYAHRPI"

Explanation

With 4 rows, the zigzag pattern changes, but the output is still formed by reading each row from top to bottom.

Show 1 more example

Example 3

Input

s = "A", numRows = 1

Output

"A"

Explanation

With only one row, the zigzag does not change the string.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.