Help me in solving SUMMODE problem

My issue

can anyone explain this problem’s solution in java? i am facing IndexOutOfBoundsException.

My code

import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner scnb=new Scanner(System.in);
		int t=scn.nextInt();
		scn.nextLine();
		while(t-->0){
		    int n=scn.nextInt();
		    scn.nextLine();
		    String st=scn.nextLine();
		    int ans=mode(st);
		    System.out.println(ans);
		}
	}
}

Problem Link: Sum of Modes Practice Coding Problem

@karthi04041
plzz refer my c++ code for better understanding of the logic

#include <bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here
	int t;
	cin>>t;
	while(t--)
	{
	    long long int n;
	    cin>>n;
	    string s;
	    cin>>s;
	    long long int sm=0,ans=0;
	    map<long long int,long long int> mp;
	    mp[0]=1;
	    for(int i=0;i<n;i++)
	    {
	        if(s[i]=='0')
	        sm--;
	        else
	        sm++;
	        ans+=mp[sm];
	        mp[sm]++;
	        
	    }
	    ans+=(n*(n+1))/2;
	    cout<<ans<<endl;
	    
	    
	}
}

bro i didnt understand completely.why aren’t you checking for all the possible substrings and why are you checking only for the complete string?

@karthi04041
by checking each substring will give u tle .
so we are checking for the substring that have even length and have equal number of 1’s and 0’s. which will contribute one extra to by answer .
So i have applied prefix check for finding such substrings.