My ans throws error saying Memory limit exceed


Is it because of the recursion ?
Should i do BFS instead of DFS ?


Not necessarily. Make sure you are passing the array in recursion by reference, not by value. If you pass by reference even the recursive method will work.


yes Its because of recursion.
when we are doing DFS then if our vector is not passed as reference then as many vector are created as many recursion are called so, to avoid that we must pass vector as reference.


I am not using recursion. I have implemented dfs using stack and while loop. And every time I check for dfs, I pass everything with reference. Still I am getting memory limit exceeded. These are the structures I am using:

  • Stack: For dfs
  • vector A : already given
  • vector vis: keeps track of visited elements. has same size as A
  • rest are some integers to process the workflow.

I don’t know how I can reduce the memory further.


Don’t use the visited vector change the existing vector to mark visited. Eg: The number -1 for visited in the same vector. You can use [] operator to change the string. string s = “abc” s[1] = x; Now, s = “axc”