# Solution by coderGirl

• #### Approach #1 Using String Buffer [Accepted]

Algorithm

In this algorithm 2 for loops are used.

1. For traversing down
2. For traversing diagonally

Java

public class Solution {
public String convert(String s, int numRows) {
StringBuffer sb[]=new StringBuffer[numRows];
int n=s.length();
char ch[]=s.toCharArray();
for(int i=0;i<numRows;i++)
sb[i]=new StringBuffer();
int i=0;
while(i<n)
{
//going down
for(int j=0;j<numRows && i<n;j++)
sb[j].append(ch[i++]);
//going diagonally
for (int j=numRows-2;j>=1 && i<n;j--)
sb[j].append(ch[i++]);
}
StringBuilder result=new StringBuilder();
for(i=0;i<sb.length;i++)
result.append(sb[i]);
return result.toString();
}
}

Complexity Analysis

• Time complexity : O(n) where n is the size of the text

• Space complexity : O(n) for storing the characters in the desired fashion and another for returning.

• @coderGirl Space complexity should be O(n). The constant should be dropped in big-O notation.

• @benjamin19890721 Thank you!

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