# Pattern Based C# Solution 89%

• Pick any string of sufficient length (~20 chars) and hand write the zigzag for rows 3,4,5,6.
You will see a pattern emerge based on the number of characters to skip for each row: e.g., the six row example looks like this:
row1: skip 10 chars at a time to end of line
row2: skip 8, then 2; repeat to EOL.
row3: skip 6, then 4, repeat to EOL.
row4: skip 4, then 6, repeat to EOL.
row5: skip 2, then 8; repeat to EOL.
row6: skip 10 chars at a time to end of line

I have referred to the max skip gap for a given number of rows as the skip constant. It is defined by as 2 * numRows - 2. (Verify, e.g., the case numRows == 4).
To obtain the first and last row, we simply skip the skip constant number of characters in the string.
For the intermediate rows, we alternate steps.
For each row, the first step decreases by two as the second step increases by the same.

``````public string Convert(string s, int numRows) {

if (numRows == 1)
return s;

var ans = new char[s.Length];

int ansIndx = 0;

int skpCnst = 2 * numRows - 2;
int s1 = skpCnst;
int s2 = 0;

for (int i = 0; i < numRows && i < s.Length; i++)
{
var step = s1;
var j = i;

while (j < s.Length && ansIndx < s.Length) {
if (i == 0 || i == numRows - 1) {
ans[ansIndx++] = s[j];
j += skpCnst;
}
else {
ans[ansIndx++] = s[j];
j+=step;
if (step == s1)
step = s2;
else step = s1;
}
}

s1-=2;
s2+=2;
}
return new string(ans);
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.