top of page

Looking to master object-oriented and system design for tech interviews or career growth?

  • Improve your system design and machine coding skills.

  • Study with our helpful resources.

  • Prepare for technical interviews and advance your career.

**We're in beta mode and would love to hear your feedback.

Zigzag String - InterviewBit Solution

Problem: Zigzag String

Problem Description:

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)


And then read line by line: PAHNAPLSIIGYIR

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"

Example 2:

ABCD, 2 can be written as


and hence the answer would be ACBD.

Solution Approach:

One thing for sure we know that we have to take only one character from each column,

So we can iterate it by rows and will take characters one by one.

The real problem here is that from the start the rows are getting incremented by 1, and once it reached the end, then it will get decremented by 1, and so on. To keep that in check we can use a flag variable, that tells us whether we should increment the row or not.

To understand it better checkout the commented code below.

Time Complexity: O(N)

Space Complexity: O(N)


Code in C++:

If you have any questions or queries, feel free to drop a comment in the comments section below.


bottom of page