rushank27 - 1 month ago 7x

C Question

I was solving the HackerRank problem given here : -- https://www.hackerrank.com/challenges/bigger-is-greater

Program statement is as follow :

Given a word, rearrange the letters to construct another word in such a way that is lexicographically greater than original one. In case of multiple possible answers, find the lexicographically smallest one among them.

If you don't understand then just go to the link; they have explained with examples.

I made the program as given below. In this program I have made two dimensional array. And variable

`t`

Code is running as it should be when

`t = 1`

But when t is greater than 1 or some large number it gives error

Code is as below :

`#include <stdio.h>`

#include <string.h>

#include <stdlib.h>

int main() {

/* Enter your code here. Read input from STDIN. Print output to STDOUT */

int i,j,n,rot;

int t;

scanf("%d",&t);

char c[t][100];

char temp;

for(int i=0;i<t;i++)

{

scanf(" %s",c[i]);

}

rot=t;

for(int t=0;t<rot;t++)

{

n = strlen(c[t]);

//printf("%d\n",n);

for(i=n-1;i>=0;i--)

{

for(j=i-1;j>=0;j--)

{

//printf("comparint %c and %c\n",c[t][i],c[t][j]); //FOR DEBUG

if(c[t][i]>c[t][j]) goto gotit;

}

}

printf("no answer\n");

continue;

gotit:

temp = c[t][i];

c[t][i]=c[t][j];

c[t][j]=temp;

n = (n-1)-j;

//printf("%s\n",c[t]); //FOR DEBUG

//printf("%d %d %d\n",i,j,n); //FOR DEBUG

for(i=0;i<n-1;i++)

{

for(int k=0;k<n-1;k++)

{

// printf("comparint %c and %c\n",c[t][j+k+1],c[t][j+k+2]);

if(c[t][j+k+1]>c[t][j+k+2] )

{

temp = c[t][j+k+1];

c[t][j+k+1]=c[t][j+k+2];

c[t][j+k+2]=temp;

}

}

}

printf("%s\n",c[t]);

}

return 0;

}

Answer

`t`

can be `10^5`

or 100,000. Your `c`

array is `c[t][100]`

, so the size of that is `100000 * 100`

, which is 10,000,000. You're probably getting a stack overflow.

As WhozCraig pointed out, the processing of each case is independent. Thus, `c`

can be a one dimensional array: `char c[100]`

. Change all `c[t][...]`

into `c[...]`

.

Adjust things so that you have one outer loop:

```
int
main()
{
int t;
char c[100];
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf(" %s", c);
// do all processing for this line ...
n = strlen(c);
}
return 0;
}
```

Source (Stackoverflow)

Comments