The runtime error that you are getting is SIGSEGV a.k.a Segmentation Fault. In layman terms, you’re accessing out of bounds. In C/C++ arrays are 0 indexed, so for A[n] you can access A[0]…A[n-1]. But A[n] throws a runtime error. It might’ve run smoothly in your compiler because accessing A[n] is undefined behavior and it’s different for different compilers.
A Simple Fix
Write your for loop as
for(int i = 0; i <n; i++)
{
// your code
}
Or
Declare the array as int ar[n + 1]
I strongly suggest the first fix.
[EDIT]: Also, you’re declaring ar[n] before taking the input! Before taking the input for n, the variable will be initialize with a junk value (if nothing is specified). You have to initialize your array after taking input for n. I guess this is why it ran smoothly in your compiler. Generally junk values are like 4576 or something. So for small inputs it’s fine as you have declared an array of size 4576. But when the given input to n is greater than the junk value, it throws an error.
def count_substring(string, sub_string): return (sum([1 for i in range(0, len(string) - len(sub_string) + 1) if (string[i:(len(sub_string)+i)] == sub_string)]))
for j in range(int(input())): print ( count_substring(input().strip(), "xy") )
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static int solve(String s){
char []arr = s.toCharArray();
int count = 0;
int i=0;
while(i<arr.length-1){
boolean flag = true;
if(i+1 < arr.length && arr[i] == 'x' && arr[i+1] == 'y'){
count++;
i+= 2;
flag = false;
}
if(i+1 < arr.length && arr[i] == 'y' && arr[i+1] == 'x'){
count++;
flag = false;
i+= 2;
}
if(flag){
i++;
}
}
return count;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
String s = sc.next();
int ans = solve(s);
System.out.println(ans);
}
}
}