Print string in zig-zag form in k rows

Given a string and a integer k, print the string in zig-zag form in k rows.


For example,



The idea is to identify a pattern in the problem. If we consider a character’s index in the output, we have observed some patterns –

  • First key of each row i is present at index i in the string.
  • For the first and the last row, the distance between each key is (k-1)*2. For example for k = 4, the difference is 6. So the first element of the first row is located at index 0, the second element is located at index 6, the third element at 12 and so on.. Similarly the first element of the last row is located at index 3, the second element is located at index 9, the third element at 15 and so on..
  • Now for all middle rows, depending upon we are going up or we are going down the index differs as evident from below code.


Below is C++ and Java implementation of the idea –


Download   Run Code


Download   Run Code



The time complexity of above solution is O(n) and auxiliary space used by the program is O(1).

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

newest oldest most voted
Notify of

I have a another code like this, can you solve this ?