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........R

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

A....C
...B....D

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)



Solution:

Code in C++:


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