‹ DS&A interview · Socratic
DSA · Strings · #189

Zigzag Conversion

Module 62 · difficulty 3/5·30:00starts on first keystroke

Given a string `s` and an integer `numRows`, write the string out in a zigzag pattern on `numRows` rows, then read it off row by row to produce the answer. The characters are written diagonally down the rows, then diagonally up, repeating. For example, `s = "PAYPALISHIRING"` with `numRows = 3` is laid out as: ``` P A H N A P L S I I G Y I R ``` Reading row by row gives `"PAHNAPLSIIGYIR"`. Implement the function `convert(s, numRows)` that returns the resulting string.

Examples
  • s = "PAYPALISHIRING", numRows = 3 "PAHNAPLSIIGYIR"Rows: "PAHN", "APLSIIG", "YIR".
  • s = "PAYPALISHIRING", numRows = 4 "PINALSIGYAHRPI"Rows: "PINA", "LSIG", "YAHR", "PI".
  • s = "A", numRows = 1 "A"A single row returns the string unchanged.
Constraints
  • · 1 <= s.length <= 1000
  • · s consists of English letters (lower-case and upper-case), ',' and '.'.
  • · 1 <= numRows <= 1000
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.