Run Time Error for v.size( ) - 1 in VSTRING

PROBLEM: Contest Page | CodeChef
doubt is regarding v.size( ) not regarding logic, my code is getting accepted but I have a small confusion in v.size( )

the following code gives me RUNTIME ERROR

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

signed main(){
int T;
cin>>T;
for(int t=0;t<T;t++){
int N,C,count=0;
cin>>N>>C;
string str;
cin>>str;
vector v;
for(int i=0;i<N;i++){
if(str[i]==β€˜1’)
v.push_back(i);
}

    for(int i=0;i<(v.size()-1);i++){
        if(v[i+1]-v[i]-1 > C)
            count++;
    }
    if(!v.empty() && ((N - v.back() - 1) + v[0]) > C)
        count++;
    if(count > 1)
        cout<<"NO"<<endl;
    else
        cout<<"YES"<<endl;
}
return 0;

}
````Preformatted text`

This code gets accepted
#include<bits/stdc++.h>
#define int long long int
using namespace std;

signed main(){
int T;
cin>>T;
for(int t=0;t<T;t++){
int N,C,count=0;
cin>>N>>C;
string str;
cin>>str;
vector v;
for(int i=0;i<N;i++){
if(str[i]==β€˜1’)
v.push_back(i);
}
int theS = v.size();

    for(int i=0;i<(theS-1);i++){
        if(v[i+1]-v[i]-1 > C)
            count++;
    }
    if(!v.empty() && ((N - v.back() - 1) + v[0]) > C)
        count++;
    if(count > 1)
        cout<<"NO"<<endl;
    else
        cout<<"YES"<<endl;
}
return 0;

}

the only difference is

    int theS = v.size();
    for(int i=0;i<(theS-1);i++){
        if(v[i+1]-v[i]-1 > C)
            count++;
    }

I wonder why it gives me run time error if I give i < v.size() - 1 and not when I give i+1 < v.size( ) or decl a separate variable for v.size( ) though it’s all same.

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

Edit:

In the meantime, the answer is likely almost exactly the same as here. Edit2: - wow, same Problem and everything XD

Sorry, I am using this forum for the first time. Thanks for the link ! Yes it’s the same problem. Got it. :slightly_smiling_face:

1 Like