Finding CB Numbers

In the code below everything works fine but when I change line 59 to line 58 it shows error for some test cases. Can you explain why?

Hello @dhruvgupta1498

The difference lies in the fact that when you declare the array in the stack memory like bool visited[n], it is garbage value initialized. While when you declare the array in heap like bool* visited = new bool[n], it is zero initialized.
So when you check for isvisited(bool* visited,int l, int r), This may return true even if this substring was never chosen because some index within l to r might get initialized with a value other than zero.

So if you replace
bool visited[n]
by
bool visited[n] = {0};
everything will work fine again.

1 Like

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.