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)
P.......A........H.......N
..A..P....L....S....I...I....G
....Y.........I........RAnd 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
A....C
...B....Dand 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)
Solution:
Code in C++:
If you have any questions or queries, feel free to drop a comment in the comments section below.



https://btckasino.net is where I ended up after a similar late-night coding session, and the flag variable trick you described for toggling between incrementing and decrementing rows is exactly the kind of small detail that makes this problem click. I've seen solutions that build out a 2D grid first, but iterating row by row with that direction check feels much cleaner and matches the O(N) complexity you mentioned. The PAYPALISHIRING example with the dots really helped me visualize why each column only contributes one character.