# Why is my codes time limit exceeded?why?

• `````` class Solution {
public:
string convert(string s, int nRows) {
string res;
int length=s.size();
if(length<1)
return res;
int interval=2*nRows-2;
for(int i=0;i<nRows;i++)
{
for(int pos=i;pos<length;pos=pos+interval)
{
res+=s[pos];
}
}
res+='\0';
return res;
}
};``````

• I just tried with your code. I get Memory Limit Exceeded

• Your code get this error because the case when nRows = 1, interval = 0, hence the inner for loop will execute infinitely.

Your code also need some other modifications.

Take a look at the below:

``````class Solution {
public:
string convert(string s, int nRows) {
string res;
int length=s.size();
if(length<1)
return res;
int interval=2*nRows-2;
if(interval == 0) interval = 1;

for(int i=0;i<nRows;i++)
{
for(int pos=i;pos<length;pos=pos+interval)
{
res += s[pos];
int temp = pos+ (nRows << 1) - (i << 1)-2;
if(i>0 && temp>pos && temp<length) res += s[temp];
}
}
//res+='\0';
return res;
}
};``````

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