ZigZag Conversion

MediumStringssimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string s and an integer numRows. Imagine writing the characters of s onto a grid in a zigzag pattern across numRows horizontal rows. The writing follows this rule: start at the top row and move **downward** one row at a time until you reach the bottom row, placing one character in each row as you go. Once you hit the bottom, move **diagonally upward** (one row up and one column to the right each step) until you reach the top row again. Repeat this down-then-diagonal-up motion until every character of s has been placed. For example, with s = "PAYPALISHIRING" and numRows = 3, the characters land like this: ``` P A H N A P L S I I G Y I R ``` After the grid is filled, read it back **row by row, left to right**, concatenating all rows into a single string and return it. For the example above, reading each row gives "PAH" + "APLSIIG" + "YIR" = "PAHNAPLSIIGYIR". Return the resulting zigzag-converted string.

Examples

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Row 0 collects P, A, H, N; row 1 collects A, P, L, S, I, I, G; row 2 collects Y, I, R. Concatenating the rows yields the answer.
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
With 4 rows the diagonal segments are longer. Reading the four rows top to bottom and concatenating gives the result.
Input: s = "A", numRows = 1
Output: "A"
With a single row there is no zigzag, so the string is returned unchanged.

Constraints

  • `1 <= len(s) <= 1000`
  • `s` consists of English letters (lowercase and uppercase), `,` and `.`
  • `1 <= numRows <= 1000`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems