What is error in this solution ? , sample test case is working correct

public static void main (String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();

    int[] a = new int[n+1];
    for(int i=1 ; i<=n ; i++)
        a[i] = sc.nextInt();

    Graph g = new Graph();
    for(int i=1 ; i<=n ; i++)
    {
        if(i+a[i]<=n)
            g.add(i , i+a[i]);
        
        if(i-a[i]>0)
            g.add(i , i-a[i]);
    }

    HashMap<Integer , Integer> visited = new HashMap<>();
    if( g.dfs(k , visited , a) )
        System.out.println("YES");
    else
        System.out.println("NO");

    //g.print();
}

static class Graph
{
    HashMap<Integer , ArrayList<Integer>> graph;
    Graph()
    {
        graph = new HashMap<>();
    }

    public void add(int a , int b)
    {
        if(!graph.containsKey(a))
            graph.put(a , new ArrayList<>());

        graph.get(a).add(b);
    }

    public boolean dfs(int i , HashMap<Integer , Integer> visited , int[] a)
    {
        visited.put(i , 1);

        if(a[i]==0) return true;

        for(int j: graph.get(i))
            if(!visited.containsKey(j))
                if( dfs(j , visited , a) )
                    return true;
        
        return false;
    }

    public void print()
    {
        for(int i: graph.keySet())
            System.out.println(i+" - "+graph.get(i));
    }

}

hello @Himanshu-Jhawar-2273952536067590

pls save this code at cb ide and share its link with me

please have a look into my code , why this is wrong

ur code is correct , due to too many function the array is copied multiple time and hence it is taking too much memory and becuase of that run error.

try to do it iteratively …(bfs)
or code the same logic in c++

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.