ITGUY13 - Editorial

Problem: CodeChef: Practical coding for everyone

DIFFICULTY:

EASY.

PROBLEM:

The chef is playing a game of occurrence. Chef has a number K and he wants to find the index of the first and the last occurrence of K in a given array of N numbers. If the index of the first and the last occurrence of K is the same then print -1.

Program:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
int t;
cin>>t;
while(t–){
int k,n;
cin>>k>>n;
int arr[n],f=-1,s=-1;
for(int i=0;i<n;i++)cin>>arr[i];
for(int i=0;i<n;i++){
if(arr[i]==k && f==-1)f=i+1;
else if(arr[i]==k)s=i+1;
}
if(f==-1 || s==-1)cout<<“-1\n”;
else cout<<f<<" “<<s<<”\n";
}
return 0;
}

1 Like

Hey @references can you please reschedule tomorrow’s push_back(1) contest a little bit as it is clashing with the codeforces Educational round scheduled tomorrow at the same time.

1 Like

Updated

1 Like

So nice of you, thanks! :smile:

can you tell what’s wrong with my code ,it passes all the test cases provided and I’m getting wrong answer every time while submitting the code.

#include<bits/stdc++.h>

using namespace std;

int main()

{

int t;

cin>>t;

while (t--)

{

    int n,k;

    cin>>k>>n;

    int arr[n];

    int start, end;

    for(int i = 1; i<=n;i++)

        cin>>arr[i];

    for(int  i = 1; i<=n;i++)

    {

        if(arr[i]==k)

            start = i;

    }

    for (int i = n; i >= 1; i--)

    {

        if(arr[i]==k)

            end = i;

    }

    

    if(start == end)

        cout<<"-1"<<endl;

    else

        cout<<end<<" "<<start<<endl;

    

}

return 0;

}

1 Like

@narayan2111 change the 10th line:
int arr[n+1];

1 Like

Okay, Thanku so much sir!

#include
using namespace std;

int main() {
// your code goes here
int no_of_test_cases {0};

cin>>no_of_test_cases;

while(no_of_test_cases--){
    int no_k {0};
    int size_n {0};
    cin>>no_k>>size_n;
    
    int arr[size_n];
    for (int i=1 ;i<=size_n;i++) {
        cin>>arr[i];
        /* code */
    }
    
    int index_of_first_occurance {0};
    
    
    for(int i =1;i<=size_n;i++){
        if(no_k == arr[i]){
            index_of_first_occurance = i;
            break;
        }
    }
    
    int index_of_last_occurance {0};
    
    for(int i =size_n;i>=1;i--){
        if(no_k == arr[i]){
            index_of_last_occurance = i;
            break;
        }
    }
    
    if(index_of_last_occurance==index_of_first_occurance){
        std::cout << -1 << std::endl;
    }
    else{
        cout<<index_of_first_occurance<<" "<<index_of_last_occurance<<endl;
    }
    
}
return 0;

}