GeetCode Hub

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
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 s, int numRows);


Example 1:

Input: s = "PAYPALISHIRING", numRows = 3

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
P     I    N
A   L S  I G
Y A   H R
P     I

Example 3:

Input: s = "A", numRows = 1
Output: "A"



  • 1 <= s.length <= 1000
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • 1 <= numRows <= 1000

class Solution { public: string convert(string s, int numRows) { // each row starts from s[k] // the first and last row increase by numRows-1 + numRows-1 = 2numRows-2 // otherwise, add two numbers each iteration: n + 2(numRows-row-1), and 2numRows+n-2 if(!s.size() || numRows==1) return s; string result; // first row for(int i=0; i < s.size(); i += 2*numRows-2) result.push_back(s[i]); for(int row=1; row < s.size() && row < numRows-1; row++) { int n = row; result.push_back(s[n]); while(n < s.size()) { int next1 = n + 2*(numRows-row-1); if(next1 < s.size()) result.push_back(s[next1]); else break; int next2 = 2*numRows+n-2; if(next2 < s.size()) result.push_back(s[next2]); else break; n = next2; } } // last row for(int i = numRows-1; i < s.size(); i += 2*numRows-2) result.push_back(s[i]); return result; } };

The main gist of this question is to get the idea of how we can use StringBuilder to append the characters at a particular level of the row. It is being explained in a detailed way in the video. 
Time Complexity: O(n)  // for traversing through each character of the string.

Space Complexity: O(n)  // for storing the result in StringBuilder.