00:00

Problem Statement

Input/Output Examples

Visual Explanation

The row index moves 0, 1, 2, 1, 0, 1, 2, …, so the whole pattern repeats every 2 × (numRows - 1) characters. Both solutions are built on that cycle.

Approaches

The first approach simulates the zigzag. The second computes directly which indexes belong to each row.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. Both approaches place every character once; the output itself needs n characters.

Interview Tips and Recommended Approach

  • Handle one row first. With numRows = 1 the cycle is 0, which would break the formula.
  • Draw a small example. Sketching 3 or 4 rows makes the cycle length obvious.
  • Only middle rows have a second character per cycle. The top and bottom rows are visited once per cycle.
  • Know the reverse problem. Rebuilding the original string from the zigzag output uses the same index formula.

Recommended Approach: Simulate the Rows

Why: it follows the pattern literally, so it is hard to get wrong under pressure, and it still runs in linear time.